Trace Viewer in Playwright

 

In Playwright for Java, the Trace Viewer is a powerful tool used for visual debugging. It allows you to record traces of your test execution (including DOM snapshots, network requests, console logs, etc.) and view them in an interactive UI. This is especially helpful when diagnosing test failures or flakiness.

















What is Trace Viewer?

  • .zip file gets created during test execution (with tracing enabled).

  • You can open this file using the Playwright Trace Viewer (npx playwright show-trace trace.zip).

  • You can see every step, including:

    • Clicks, fill, type actions

    • Screenshots

    • API requests/responses

    • DOM state at each action


Steps to Use Trace Viewer in Java

  • Start tracing before test execution.
  • Stop tracing after the test and export the trace file.
  • View trace using npx playwright show-trace trace.zip in terminal.



Java Code Example


import com.microsoft.playwright.*;

public class TraceViewerExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();

            // Start tracing
            context.tracing().start(new Tracing.StartOptions()
                .setScreenshots(true)
                .setSnapshots(true)
                .setSources(true));

            Page page = context.newPage();
            page.navigate("https://playwright.dev");

            // Perform some actions
            page.locator("text=Docs").click();
            page.locator("input[placeholder='Search']").fill("trace viewer");
            page.keyboard().press("Enter");

            // Stop tracing and export it
            context.tracing().stop(new Tracing.StopOptions().setPath(Paths.get("trace.zip")));

            browser.close();
        }
    }
}


Viewing the Trace

After executing the above code, a file named trace.zip is created.

To view it:

npx playwright show-trace trace.zip

This opens an interactive UI in your browser where you can step through every action.

No comments:

Post a Comment