Search code examples
typescriptplaywright

For loop for multiple tabs on Playwright


I would like to create a function that includes for loop to open multiple browser tabs (the number of tabs should be specified as a parameter). My goal is to change these lines of code:

test('Test name', async ({ context }) => {
    const page2 = await context.newPage();
    await page2.goto(urlText);
    const page3 = await context.newPage();
    await page3.goto(urlText);
});

Also, I would like to use POM and add this function to my commonOperations.ts file

export class CommonOperations {
    readonly page: Page;
    constructor(page: Page) {
        this.page = page;
    }

    async login() {
        const email = process.env.EMAIL;
        const password = process.env.PASSWORD;
        const url = process.env.URL;
        await this.page.goto(url);
        await this.page.fill(sso.inputEmailField, email);
        await this.page.click(sso.submitButton);
        await this.page.fill(sso.inputPasswdField, password);
        await this.page.click(sso.submitButton);
        await this.page.click(sso.submitButton)
    }
}

I was trying to do something like that, but it didn't work out (also there was an issue with undefined context when I am using it in commonOperations.ts file):

for (let i = 0; i <= 1; i++) {
        const page[i] = await context.newPage();
        await page[i].goto(urlText)
        const nickname = randomName(10);
        await page[i].fill("input[data-testid='text-input-field']", nickname);

Maybe somebody has some suggestions, how can I do that? Thank you!


Solution

  • You are getting 'page' implicitly has an 'any' type because page[i] does not exist. You don't need to assign i to it. You are just iterating over the loop using i but can do whatever you want inside it with regard to page:

    test.beforeEach(async ({ context }) => {
        for (let i = 0; i <= 1; i++) {
          const page = await context.newPage();
          await page.goto(urlText)
          const nickname = randomName(10);
          await page.fill("input[data-testid='text-input-field']", nickname);
      }