QA Wolf logo

QA Wolf

/

Star

2.7k

Reuse Helper Code

Helpers in QA Wolf are pieces of code that can be shared between tests.

If you reuse similar code in multiple tests (such as code to log in), you should probably move it to your team's helpers.

Edit Helpers

At QA Wolf, we need to log in at the beginning of most of our tests. In particular, we log in by setting a token in local storage:

await page.evaluate(() => localStorage.setItem("token", "myToken"));
await page.reload();

Rather than paste the same code into multiple tests, we can create a log in function that we reuse across tests. We'll store this function in our team's helpers file. You can access this file in the "Helpers" tab of the test editor.

Helpers tab

Let's add the following logIn function to our helpers. It takes the Playwright Page as an argument and sets a token in local storage:

async function logIn(page) {
await page.evaluate(() => localStorage.setItem("token", "myToken"));
await page.reload();
}

Now the logIn function will be available to use in all of our tests.

Helpers code

Use Helpers

In the "Code" tab of the test editor, we can now replace the log in code:

await page.evaluate(() => localStorage.setItem("token", "myToken"));
await page.reload();

With a call to our logIn helper:

await logIn(page);

Now our test looks like the following.

Use function in helpers

Pass Variables to Helpers

Helpers are just JavaScript code, so you can also create functions that take any number of variables.

Below is a modified version of our logIn function that takes a specific token as an additional argument. This is useful if we want to log in as different users in different tests:

async function logInWithToken(page, token) {
await page.evaluate((token) => localStorage.setItem("token", token), token);
await page.reload();
}

In our test, we can now call logInWithToken and pass it the token of our choice:

await logInWithToken(page, "adminToken");

Helpers also have access to environment variables. These variables are found under process.env.

The function above can be modified to read the token from an environment variable rather than from an argument:

async function logInWithToken(page) {
await page.evaluate(
(token) => localStorage.setItem("token", token),
process.env.TOKEN
);
await page.reload();
}