Search code examples
playwrightplaywright-typescript

Is there any reason why toBeInViewport() shouldn't replace toBeVisible() in most circumstances?


I have been using .toBeVisible() to check if an element is displayed on the page. However in a few circumstances the element is visible to human eye and intractable. In these cases I've been using toBeInViewport().

Would there be a downside to replacing all instances of toBeVisible() with toBeInViewport()?


Solution

  • A simplistic way to show a fundamental difference between those two is by running this test:

    import { expect, test } from "@playwright/test";
    
    test("Test 1", async ({ page }) => {
      await page.goto("https://playwright.dev/docs/actionability");
     
      // A locator further down on the webpage:
      const locatorToFind = page.getByText("Element is considered receiving pointer events");
    
      await expect.soft(locatorToFind).toBeInViewport(); 
      // Fails as you need to scroll down to see the text
      
      await expect.soft(locatorToFind).toBeVisible(); 
      // Passes as the locator is visible on the page if you scroll
    });
    
    

    Which, as pointed out in an earlier answer, results in toBeInViewport() risks being more flaky.