javascriptui-automationplaywrightplaywright-testplaywright-typescript

Open a tab, Switch between tabs, close tab on browser not working on Playwright Typescript


I'm opening a tab (t1) using beforeEach, from that I'm opening another tab (t2). Now, I want to perform some actions on (t2) and switch to (t1). And then, close a (t2) tab.

  test.beforeEach(async ({ page }) => {
   await page.goto(BASE_URL + "/t1");
  });


test("switch between tabs", async ({ context }) => {

  const page = await context.newPage();

  const [newtab] = await Promise.all([
    context.waitForEvent('page'),    
    await page.goto(BASE_URL + "/t2"),
    await page.getByTestId('id_here').click(),
    await page.getByTestId('id1_here').fill('test')
 ])
 //come back to tab (t1)
 //perform actions on tab (t1)
 //close tab (t2)

});

Solution

  • You can use context.pages() to keep track of the open windows within the test context. This will follow even the window opened during your beforeEach.

    test.beforeEach(async ({ page }) => {
       await page.goto(BASE_URL + "/w1");
    });
    
    test('Foo', async ({ context }) => {
      const w2 = await context.newPage();
      const w1 = context.pages()[0]; // assumes that the first page opened always occupies the first position in the array
      // alternatively...
      const w1Alt = context.pages().find(x => x.url() === BASE_URL + "/w1")
    });
    

    Alternatively, you could keep track of the w1 window by assigning the page from your beforeEach to a variable.

    let w1: Page;
    
    test.beforeEach(async ({ page }) => {
      w1 = page;
      await w1.goto(BASE_URL + "/w1");
    });
    
    test('Foo', async ({ context }) => {
      const w2 = await context.newPage();
      await w2.goto(BASE_URL + "/w2");
      // use w1 and w2 to reference each page
      await expect(w1).toHaveURL(BASE_URL + "/w1");
      await expect(w2).toHaveURL(BASE_URL + "/w2");
    });