Rayrun

How can I share a variable between beforeEach and test blocks in @playwright/test?

Answer

Sure, you can share a variable between beforeEach and test blocks in @playwright/test. Declare the variable outside of both blocks to make it accessible. Here's an example:

const myConstant = 'some value';

test.beforeEach(async ({ page }) => {
  console.log(myConstant); // logs 'some value'
});

test('my test', async ({ page }) => {
  console.log(myConstant); // logs 'some value'
});

In this example, myConstant is accessible from within each block.

If you need to set the variable value dynamically, use a beforeAll hook:

let myConstant;

test.beforeAll(async () => {
  const someValue = await getValueFromServer();
  myConstant = calculateValue(someValue);
});

test.beforeEach(async ({ page }) => {
  console.log(myConstant); // logs dynamically calculated value
});

test('my test', async ({ page }) => {
  console.log(myConstant); // logs dynamically calculated value
});

Here, myConstant is set based on an asynchronous operation and a calculation function. It can be accessed from within any subsequent block.

Remember, if you need to use values that are only available inside one specific test or beforeEach hook, store them in variables scoped only to that specific block to avoid errors or unexpected behavior.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].