How to include target elements in screenshots in a Playwright step

Prev Next

When running a Playwright code step, if the target element is off-screen (requires scrolling), it may not be included in the Test results screenshot.

You can resolve this issue by explicitly scrolling until the target element enters the viewport.

Sample code

Below is sample code that scrolls until the target element enters the viewport before verifying the element's text. Please replace placeholders such as "foo", "target", and the provided code content with values suitable for your specific use case.

// 1. Identify the element first
const target = page.getByRole("heading", {
  name: "foo"
});
                    
// 2. Scroll until the target element enters the viewport
await target.scrollIntoViewIfNeeded();

// 3. Verify the element's text
await expect(target).toContainText("foo", {
  useInnerText: true
});

Code explanation

  1. Identify the element: Define the element you want to operate on or verify using methods such as getByRole.

  2. Execute scrolling: By calling scrollIntoViewIfNeeded(), Playwright automatically scrolls to that location only if the element is not currently visible.

  3. Verification: Perform the verification while the element is within the screen.