Playwright is a Node.js library to automate Chromium, Firefox, and WebKit with a single API. As with any development process, debugging is an integral part of working with Playwright. Here are the debugging options available.
1. Browser-level debugging
Playwright provides a way to see what’s happening in the browser context by enabling the head mode, slowing it down and capturing browser-level logs.
const playwright = require('playwright');
(async () => {
const browser = await playwright.chromium.launch({
headless: false, // default is true (browser won't be visible)
slowMo: 50 // slow down by 50ms
});
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
2. Network-level debugging
To debug network interactions, you can use page.route()
to intercept certain network requests.
await page.route('**/api/**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://example.com');
3. Protocol-level debugging
You can enable verbose logging to get the details of the protocol traffic between Playwright and the browser. This can be done by setting DEBUG
environment variable to pw:api
before running the script.
For example, in Unix-based systems:
DEBUG=pw:api node myscript.js
And in Windows Command Prompt:
set DEBUG=pw:api
node myscript.js
4. Tracing
Playwright can record a trace of your script, which includes screenshots, network requests, console logs, page operations and more. This can be later inspected using Playwright CLI.
// Start tracing
await page.tracing.start({ screenshots: true, snapshots: true });
// Interact with the page
await page.goto('http://example.com');
// Stop tracing
await page.tracing.stop({ path: 'trace.zip' });
The trace can be viewed with:
npx playwright show-trace trace.zip
5. Assertions and Logging
Good old console logging and assertions are also available in Playwright.
console.log('Navigating to example.com');
await page.goto('http://example.com');
console.assert(await page.title() === 'Example Site', 'Unexpected title');
Remember to combine these techniques to make your debugging process more efficient.