Search code examples
typescriptwhile-loopplaywright

How do I click on "Next" button until it disappears in playwright (typescript)


Here is the code I am using to click next button until it disappears on pagination.

Then, I can verify the record on the last page

The issue is, when it is in the last page, still tries to find the locator, and gives error because of the timeout.

But, I need to exit from the loop when it is disappeared

while (true) {
      try {
        await page.locator("//div[@class='next-button']").click();
        await page.waitForTimeout(1000);
      } catch (error) {
        break;
      }
    }

Solution

  • This code uses page.waitForSelector to wait for the selector to be present and visible. If the selector is not found within the specified timeout (2 seconds in this case), it returns null. The code then checks if nextButton is truthy, meaning the element is present and visible. If so, it clicks on it, waits for a timeout, and continues the loop. If nextButton is falsy (null), the loop breaks.

    Here's how it works:

    1. page.waitForSelector returns a promise that resolves to the element handle when the selector is found and meets the specified conditions (in this case, being visible). If the selector is not found within the specified timeout, it rejects the promise.

    2. The .catch(() => null) part catches any rejected promise (error) and provides a fallback value of null. In other words, if the selector is not found within the specified timeout, the promise is rejected, and the catch block ensures that the nextButton variable is set to null.

    So, if page.waitForSelector successfully finds the element and resolves the promise, nextButton will contain the element handle. If there's an error (e.g., the element is not found within the timeout), nextButton will be null.

    while (true) {
    
      const nextButton = await this.page.waitForSelector("//div[@class='next-button']", { state: 'visible', timeout: 2000 }).catch(() => null);
        
      if (nextButton) {
        await nextButton.click();
        await this.page.waitForTimeout(1000);
      } else {
        break;
      }
    }