cabs
cabs

Reputation: 41

Playwright js - im trying to validate when clicking on a button it opens a new tab , then validates the title

So i have written a function that in short clicks an FAQs button and validate that the new tab is open on the same browser Context. the issue i have when running my test is i get:

TypeError: Cannot read property 'title' of undefined

Heres my function - PATH src/tests/logoutAndFaqs.spec.ts:

async shouldSeeFaqsInNewTab() {
     const browserName = await chromium.launch();
     const context = await browserName.newContext();
     const pages = await context.pages();

     await this.click(HomeScreen.faqButton);
     await this.page.waitForTimeout(1000);

     expect(await pages[1].title())?.toBe("Title");
  }

and heres is the function getting called - PATH src/pages/home.page.ts:

import test from "../../helpers/base.page";

test.describe("Ensure you land on the home page when logged in", () => {
  test.beforeEach(async ({ Home }) => {
    await home.gotoHomePage();
  });

  test.only("Validate that FAQs opens in a new tab", async ({ home }) => {
    await home.shouldSeeFaqsInNewTab();
  });
});

i know that this line expect(await pages[1].title())?.toBe("Title") specifically is accessing the tab opened within the window and within the browserContext its validating the title expecting a string to equal "Title".

specifically title() is causing an error due to being an unassign value. im trying to understand why this error? and how to fix it. thanks

Upvotes: 2

Views: 1901

Answers (2)

cabs
cabs

Reputation: 41

So i manage to to solve this part by using the Promise.all method, which resolves by waiting for the popup when clicking on the button that opens a new tab, .waitForEvent("popup") method - heres the method i wrote to solve this:

async navigateAndValidatePopUpPage() {
        const [popUpPage] = await Promise.all([this.page.waitForEvent("popup"), this.click(rmsHomeScreen.newTabPageButton)]);
        await this.waitForDomToLoad(popUpPage);
        expect(await popUpPage.title()).toBe("Enter title of the popup page here");
      }

as for this line await this.waitForDomToLoad(popUpPage);, specifically this .waitForDomToLoad, is simply assign to this method :

 async waitForDomToLoad(pageToWait: Page) {
        await pageToWait.waitForLoadState("domcontentloaded");
      }

waiting for event
Promise.all()
waitForLoadState

Upvotes: 1

Alan Kalbermatter
Alan Kalbermatter

Reputation: 11

In this cases given your info, you should check if you're instantiating your page object correctly with the correct innerHTML. If not, it could not create the object properly and because of that you're getting undefined.

Upvotes: 1

Related Questions