playwright icon indicating copy to clipboard operation
playwright copied to clipboard

[Question] How to use a reusable page in a test fixture?

Open aoj2 opened this issue 1 year ago • 1 comments

Hi, in our test specs we are setting up the Page object in the beforeAll hooks, I would like to access that page in an automatic test fixture, but not sure how to achieve that...? (Note: If using the page fixture in the test it works, but that's unfortunately not a viable solution for us atm).

In the example below two separate pages will be created...

Thanks in advance!

// test.spec.js
let page;

  test.beforeAll(async ({ browser }) => {
    page = await browser.newPage();
  });

  test.afterAll(async () => {
    await page.close();
  });

 test("Navigate to page", async () => {
    await page.goto(“/“);
)};
// test.fixture.js

exports.test = base.test.extend({
  testFixture: [
    async ({ page }, use, testInfo) => {
      console.log(testInfo.title);
      console.log("Before Each");

      await use();
 
      console.log("After Each");
      await page.evaluate(() => {});
    },
    { scope: "test", auto: true },
  ],
});

aoj2 avatar May 15 '23 06:05 aoj2

@aoj2 Since you are reusing the page between tests, any test fixture won't be able to access it. Note that reusing page between tests is a discouraged practice.

You can work around this issue by placing code before await use() in a test.beforeEach() call in the same file where your test.beforeAll() that creates the page is located. Same goes for test.afterAll().

// test.spec.js
  let page;

  test.beforeAll(async ({ browser }) => {
    page = await browser.newPage();
  });

  test.beforeEach(async () => {
    // use page here
  });

  test.afterEach(async () => {
    // use page here
  });

  test.afterAll(async () => {
    await page.close();
  });

 test("Navigate to page", async () => {
    await page.goto(“/“);
  )};

Let me know whether this helps.

dgozman avatar May 15 '23 16:05 dgozman

It seems like the issue has been resolved. If you still encounter problems, please file a new issue with a repro and link to this one.

dgozman avatar May 19 '23 17:05 dgozman