Playwright QA Automation QA Tools

How to Handle Trace Viewer in Playwright? 

Playwright-Trace-Viewer

Web development is always changing. It’s crucial to ensure that your web applications are reliable and fast. The playwright is a strong testing framework. It has emerged as a go-to tool for developers aiming to achieve this goal. A standout feature of the Playwright is the Trace Viewer. It is a powerful tool designed to simplify debugging. In this blog post, we’ll dig into the details of the Trace Viewer. We’ll explore its features, benefits, and how to use it to improve your testing workflow. 

What is the Trace Viewer? 

The Trace Viewer in Playwright is a visual tool. It lets developers capture and inspect the execution traces of their tests. It delivers a thorough account of test run events, simplifying issue diagnosis.  

Key Features of Trace Viewer

  • Step-by-Step Execution: The Trace Viewer records each step in your test. It includes actions like clicks, navigations, and assertions. This allows you to see exactly what happened at each stage of your test. 
  • Screenshots and Snapshots: For each step, Trace Viewer captures screenshots. It lets you visually check your app’s state at any time. 
  • Network Activity: Trace Viewer logs all network requests and responses. It shows the data exchanged between your application and the server.  
  • DOM Snapshots: DOM Snapshots capture the DOM state for each step. It helps find issues with element visibility, layout, and more.  
  • Logs and Console Output:  It captures all console logs and errors. This gives you a full picture of the test.  

 Benefits of Using Trace Viewer:

  • Enhanced Debugging: It provides a detailed record of each test step. Trace Viewer makes it easier to see where and why a test failed. 
  • Time-Saving: It saves time. Locate existing issues rather than recreating them from scratch. You can do so with the visual and interactive interface. 
  • Improved Test Reliability: Trace Viewer gives insights. They’ve let you refine tests to handle edge cases and improve reliability. 
  • Collaboration: Sharing trace files with your team allows for collaborative debugging. Everyone can see the same trace. 

 Understanding Trace Viewer:

Trace Viewer in Playwright captures and inspects execution traces of tests. This feature is powerful. It shows a full view of each action, network activity, and page state during your test runs. Integrating Trace Viewer with TypeScript enhances debugging capabilities and ensures robust testing.  

Setting Up Trace Viewer:

1. Setting Up Playwright with TypeScript:

If you haven’t installed Playwright yet, run the following command:

npm init –y 

npm install playwright

npm install typescript ts-node @types/node

2. Create a tsconfig.json file:

{ 

"compilerOptions": {

"target": "ES6",

"module": "commonjs",

"outDir": ". /dist",

"rootDir": ". /src",

"strict": true,

"esModuleInterop": true,

"skipLibCheck": true

},

"include": ["src"]

}

3. Enable Tracing in Your Tests:

Turn on tracing in your browser to use Trace Viewer. You need to turn on tracing in your Playwright test. You can do this by adding the trace option to your test configuration.  

import { test, expect, Browser, Page, Locator } from '@playwright/test' 

import { chromium } from '@playwright/test'

test('login test', async () => {

const browser: Browser = await chromium.launch({ headless: false, channel: 'chrome' });

const context = await browser.newContext();

const page: Page = await context.newPage();

// Start tracing before navigating to the page

await context.tracing.start({screenshots: true, snapshots: true });

await page.goto("https://demo.applitools.com/");

await page.locator('[placeholder="Enter your username"]').fill('Rahul'); //fill the input box with text

await page.locator('[placeholder="Enter your password"]').fill('5678'); //fill the input box with text

await page.waitForTimeout(4000);

await page.locator("text=Sign in"). click();

// Stop tracing and export it into a file

await context.tracing.stop({path: 'trace.zip'});

await browser.close();

});

4. Running Your Test:

Execute your test script. The tracing data will be saved to a file (e.g., trace.zip) 

Viewing the Trace:

To view the trace, use the Playwright CLI:

npx playwright show-trace.zip 

This command opens the Trace Viewer in your default browser, allowing you to explore the captured trace.

Understanding Trace Viewer Components:

  • Actions: Action is the steps taken during testing. They include clicks, navigations, and typing. The Trace Viewer records these to provide a step-by-step overview of the test flow.  
await page.goto("https://demo.applitools.com/"); 

await page.locator('[placeholder="Enter your username"]').fill('Rahul');

await page.locator('[placeholder="Enter your password"]').fill('5678');

await page.locator("text=Sign in").click();
  • Screenshots: Screenshots capture the visual state of the page at specific points during the test. Setting screenshots to true in the tracing configuration helps. They verify the UI’s appearance.  
Await page. screenshot({ path: ‘demo.png’ }); 
  • Snapshots: Snapshots capture the DOM(Document Object Model) state of the page at specific points during the test. They show the page’s structure and styles in detail. They help find layout issues 
Await context.tracing.start({snapshots: true }); 
  • Calls: Calls refer to the specific actions or function calls made during the test execution. The system logs these in the trace.  
await page.goto("https://demo.applitools.com/");   

await page.locator("text=Sign in").click();
  • Logs: Logs capture console output from the page. It can include information, debug output, and custom logs.  
Await page.evaluate(()  => console.log(‘page loaded’)); 
  • Errors: Error console captures any errors logged to the console during the test execution.  
Await page.evaluate(()  => console.error(‘Simulated error’)); 

Example of Test Script with Comprehensive Tracing: 

Here’s a complete example that combines actions, screenshots, snapshots, calls, logs, and errors: 

import { test, expect, Browser, Page, Locator } from '@playwright/test' 

import { chromium } from '@playwright/test'

test('login test', async () => {

const browser: Browser = await chromium.launch({ headless: false, channel: 'chrome' });

const context = await browser.newContext();

const page: Page = await context.newPage();



// Start tracing before navigating to the page

await context.tracing.start({ screenshots: true, snapshots: true });

// Actions

await page.goto("https://demo.applitools.com/");

await page.locator('[placeholder="Enter your username"]').fill('Rahul');

await page.locator('[placeholder="Enter your password"]').fill('5678');

await page.waitForTimeout(4000);

await page.locator("text=Sign in").click();

// Enable console log and error capturing

page.on('console', message => {

if (message.type() === 'log') {

console.log(`LOG: ${message.text()}`);

}

else if (message.type() === 'error') {

console.error(`ERROR: ${message.text()}`);

}

else {

console.log(`${message.type().toUpperCase()}: ${message.text()}`);

}

});

// Actions

await page.evaluate(() => console.log('Page loaded'));

await page.evaluate(() => console.error('Simulated error'));


// Stop tracing and export it into a file

await context.tracing.stop({ path: 'trace.zip' });

// Actions

await page.screenshot({ path: 'demo.png' }); // Manually taking a screenshot

await browser.close();

});
Playwright Trace Viewer

Analyzing the Trace:

In the Trace Viewer, you’ll find: 

  1. Actions Tab: The Actions Tab lists all actions from the test. It gives context for each step. 
  2. Screenshots Tab: This tab shows automatic and requested test screenshots.  
  3. Snapshots Tab: Displays the DOM snapshots captured during the test. . 
  4. Logs Tab: Displays all console logs captured during the test execution. 
  5. Errors Tab: Displays console logs, revealing issues for swift diagnosis. 

Conclusion: 

Trace Viewer in Playwright when combined with TypeScript, offers a powerful solution. It helps with debugging and improving your testing workflow. It captures detailed execution traces. This makes it easier to find and fix issues. It leads to more robust and reliable web applications. Use this tool to streamline testing. It will improve your projects.  

rahul-chaubey

Associate Test Engineer