Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you run multiple tests in one browser context Playwright JavaScript?

Is it possible to run multiple tests in one browser window for Playwright/test?

Currently it will hit browser.close(); after every test even though they are testing on the same page which puts a lot of extra time on the tests.

test.beforeAll(async ({ browser }) => {
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.com');
});

test('nav test', async ({ page }) => {
  const name = await page.innerText('.navbar__title');
  expect(name).toBe('Playwright');
});

test('header test', async ({ page }) => {
  const name = await page.innerText('.navbar__header');
  expect(name).toBe('Playwright');
});
like image 333
el_nuggs Avatar asked Feb 19 '26 04:02

el_nuggs


1 Answers

When you create a test like this, test('header test', async ({page}) => {, you're specifying page and telling it to create a new page context.

Remove the page from the test, and share the one you create from your .beforeAll.

Try this:

test.describe('1 page multiple tests', () => {
    let page;
    test.beforeAll(async ({ browser }) => {
        const context = await browser.newContext();
        page = await context.newPage();
        await page.goto('https://example.com');
    });

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

    test('nav test', async () => {
        const name = await page.innerText('h1');
        expect(name).toContain('Example');
    });

    test('header test', async () => {
        const name = await page.innerText('h1');
        expect(name).toContain('Domain');
    });
});

Run it like this:

npx playwright test .\StackTests_SinglePage.spec.ts --headed

(you can see the name of my file in there)

You might need to toggle it down to one worker if it tries to parallel run your test.

For me, that code opens one browser, one page, passes both tests, and then closes out.

Enter image description here

like image 113
RichEdwards Avatar answered Feb 21 '26 16:02

RichEdwards