playwright

What is the best way to Assert a tab has been successfully closed using playwright


What is the best way to get Playwright to assert that a Tab has successfully been closed.

An example scenario

A user clicks an account settings link which opens up a new tab. There is a link to navigate back to the home screen in that 2nd tab. If the Homescreen is already open in tab 1 then tab 2 is closed. If the homescreen is not open then the user is navigated to it in tab 2.

What is the correct way to assert the first scenario, and confirm that the tab has been closed?


Solution

  • Here's a full example in typescript/javascript:

    This code opens two tabs on a shared BrowserContext, than stores the count of open tabs using browserContext.pages() method, closes the second one using page.close() method, and finally asserts that current open tabs count is less than the stored count using toBeLessThan Playwright GenericAssertions method.

    test("Assert tab count decreased after closing a tab", async () => {
      const browser = await chromium.launch();
      const context = await browser.newContext();
    
      // Open first tab (page)
      const page1 = await context.newPage();
      await page1.goto("https://google.com");
    
      // Open second tab (page)
      const page2 = await context.newPage();
      await page2.goto("https://playwright.dev/");
    
      // Store current pages count
      const initialPagesCount = context.pages().length;
    
      // Close the second tab (page)
      await page2.close();
    
      // Assert the page count decreased
      expect(context.pages().length).toBeLessThan(initialPagesCount);
    });