In this tutorial, we'll learn how to reuse code between tests.
Let's reuse a sign in function that sets a token in local storage:
async function signIn(page) {await page.evaluate(() => localStorage.setItem("token", "myToken"));await page.reload();}
Rather than paste this code into every test that uses it, you can store it in your team's helpers.
Now the signIn
function will be available to use in all of our tests.
From the test's "Code" tab, we can now replace this:
await page.evaluate(() => localStorage.setItem("token", "myToken"));await page.reload();
With a call to our signIn
helper:
await signIn(page);
Now our test looks like the following.
Helpers are just JavaScript code, so you can also create functions that take any number of variables.
Below is a modified version of our signIn
function that takes the desired token as an additional variable and sets it in local storage:
async function signInWithToken(page, token) {await page.evaluate((token) => localStorage.setItem("token", token), token);await page.reload();}
In our test, we can now call signInWithToken
and pass it the token of our choice:
await signInWithToken(page, "adminToken");
Helpers also have access to environment variables. These variables are found under process.env
.
We could modify the function above to read the token from an environment variable rather than from an argument:
async function signInWithToken(page) {await page.evaluate((token) => localStorage.setItem("token", token),process.env.TOKEN);await page.reload();}