playwrightplaywright-test

How to pass a value to a test from beforeeach


I am writing a test in Playwright and have a before each. I need a value that is generated in the beforeEach function to be available in the test function itself.

test.beforeEach(async ({ page, request }) => {
  const user = await createUser(request);
  // pass the user variable to each test
});

test.describe('do something', () => {
  test('do something 1', async ({ page }) => {
    // have access to the variable here
  });
});

Solution

  • You can achieve this by defining the variable outside of the beforeEach function and then assigning it within the beforeEach function. This will make it accessible to all the tests within the same scope. Example:

    // Define the user variable outside the beforeEach function
    let user;
    
    test.beforeEach(async ({ page, request }) => {
      // Generate the user and assign it to the user variable
      user = await createUser(request);
    });
    
    test.describe('do something', () => {
      test('do something 1', async ({ page }) => {
        // Use the user variable in your test
        console.log(user);
      });
    });
    

    Hope it helps.