Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  });
});
like image 583
Matt Avatar asked Sep 11 '25 03:09

Matt


1 Answers

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.

like image 122
InvstIA Avatar answered Sep 13 '25 17:09

InvstIA