Thursday, May 1, 2025

How to use Playwright to test multiple browser windows?

Here is a way you can test multiple windows. Not multiple tabs in the same window. But multiple windows, each with its own storage and cookies. A use case would be if your website has implemented chat functionalities, and you want to see if the messages are delivered correctly. You can have two browsers logged in with two users and have them talk with each other. How would we achieve that in Playwright in one single test?

How to use Playwright to test multiple browser windows?


By using our browser and page objects. Here is an example of code.

import { test, expect } from "@playwright/test";

test("Two users chat functionalities", async ({ browser }) => {
    // we open two browsers each with its own storage and cookies
    const user1Context = await browser.newContext()
    const user1Page = await user1Context.newPage()
    const user2Context = await browser.newContext()
    const user2Page = await user2Context.newPage()

    // we open the chat
    await user1Page.goto("https://www.webchat.com/chat")
    await user2Page.goto("https://www.webchat.com/chat")
    // other login credentials details would go here

    // we start talking with each other in sequence
    
    await user1Page.getById("input").type("Hello user 2")
    await user1Page.getById("sendMsgBtn").click()
    
    await expect(user2Page.getByText("Hello user 2")).toBeVisible()
    await user2Page.getById("input").type("Oh ! Hello user 1")
    await user2Page.getById("sendMsgBtn").click()

    await expect(user1Page.getByText("Oh ! Hello user 1")).toBeVisible()

  });


This is all about accessing multiple browser in playwright.


No comments:

Post a Comment