Home > Mobile >  Cant implement conditional code inside playwright's page object model
Cant implement conditional code inside playwright's page object model

Time:08-09

I'm trying to implement conditional code in playwright inside of page object. It depends on if element is found on page or not. The problem is - returned value is always the same, no matter if element is present or not. Here is my code:

    this.pagePlaceholder = page.locator('.s-wrapper.s-wrapper_placeholder');


  async clearUpPage() {
    const placeholdersNumber = await this.pagePlaceholder.count();
    console.log(placeholdersNumber);

      
        if (placeholdersNumber < 1) {
          await this.mainSection.hover({
            position: {
              x: 200,
              y: 150,
            },
          });
    
          await this.page.click('.section-options__btn._del:visible');
          await expect(this.pagePlaceholder).toBeVisible();
        }
      }

So the problem is - count() always returns 0, even if element of that class is present on that page. I also tried solutions with "if (this.pagePlaceholder)" and "if (this.pagePlaceholder.isVisible())" and those also return same value no matter what. If I use 'waitForSelector" inside "if" - it throws timeout error if selector is not found, so test is failed instead of case being skipped.

CodePudding user response:

Try adding a

await this.pagePlaceholder.waitFor({ state: "visible" });

Before you perform the count, I suspect that the screen is still loading when you try to count it (its not there).

Failing that you might want to enable trace recording and look at that!.

CodePudding user response:

So I managed to find a solution on Playwright's github. The solution is - to use separate "delay" function like that:

import { delay } from './utils';

 async clearUpPage() {
    await delay(5000, null);

    const placeholdersNumber = await this.pagePlaceholder.count();
    console.log(placeholdersNumber);

    if (placeholdersNumber < 1) {...}
}

delay() function is imported from the file utils.ts:

export function delay<T>(milliseconds: number, value: T): Promise<T> {
    return new Promise(function(resolve) { 
        setTimeout(resolve.bind(null, value), milliseconds)
    });
}

Original answer

Note that milliseconds value matters. Value from original answer (2000) didn't help in my case.

  • Related