Guide to Playwright Debugging
On This Page What is Playwright?What is Debugging and Trac
How to start with Playwright Debugging in 2026?
I used to think debugging was but about supply logs and rerunning exam until they passed. But Playwright made me realize something else: debug only works when the right tool is used at the correct moment. Browser tools, logs, screenshots, and video recordings are all available, yet failures still occupy hours to understand.
Debugging is an essential constituent of test mechanization, and Playwright provides knock-down ways to investigate failures.
Overview
Methods for debugging Playwright tests
- Playwright Inspector
- Playwright Trace Viewer
- Browser Developer Tools
- Optic Studio Code debugger
- Verbose API logs
- Headed Mode
- UI mode
Mutual Challenges in Playwright Debugging
- Flaky tests
- Element Not Visible or Detached
- Debugging Timeouts
- API and Network Issues
- Browser Compatibility and Environment Differences
- Complex Authentication Flows
This article shows how to use those debugging characteristic efficaciously to find real topic quicker instead of relying on repeated reruns.
What is Playwright?
is an open-source tryout automation tool shipped with an Apache licence. While Playwright launch browsers in the by default, it can besides run them in headful mode. By passing a flag, when the browser is launched, Playwright can be used to run browsers in the headful mode for tests.
Browsers supported for Playwright
- It has gained grip due to benefits, such as support for multiple speech such as Java, C #, NodeJS, and Python.
- Playwright tests can be run on Firefox, Webkit, and Chromium-based browser.
- It is compatible with Windows, Linux, and macOS and can be integrated with primary CI/CD server such as, Azure Pipeline, TravisCI, etc.
Note: With BrowserStack, Playwright Browser Compatibility extends to WebKit, Mozilla Firefox, and Chromium for Playwright versions 1.10.0 & # 8211; 1.25.1
What is Debugging and Tracing in Playwright
Debugging and tracing are indispensable for creating reliable and efficient test handwriting in.
Debugging helps identify and fix issues like failing tests, timing problems, or unexpected browser behavior, ensuring your scripts run as intended.
Tracing, on the other manus, provides a detailed step-by-step disc of test executing, include screenshots and logs, get it easier to study and understand failure.
Together, these puppet relieve time, ameliorate test accuracy, and help catch potential issues early in the development round. By mastering debugging and trace in Playwright, you can make racy that ensure the quality of your coating.
Read More:
How to run Playwright debug mode?
Playwright is a powerful end-to-end testing framework that grant developer to automate interaction with web browsers. One of its important features is the ability to run exam in & # 8220; debug mode & # 8221; which provide detailed insights into examination executing, helping identify and adjudicate issues efficiently. Debug fashion enable a bit of debug techniques, each designed to suit different scenarios and workflows.
Below are some of the method for debugging Playwright test:
- Playwright Inspector
- Playwright Trace Viewer
- Browser Developer Tools
- Visual Studio Code debugger
- Verbose API logs
- Headed Mode
- UI mode
1. Debugging habituate Playwright Inspector
Playwright Inspector is a GUI instrument that get with the framework by default, and no additional configuration is required to use this puppet.
To establish your test with Playwright Inspector mode, you need to prefix the test command withPWDEBUG=1depend on the command-line tool you are using, the syntax might differ.
Powershell
$ env: PWDEBUG=1 npx run tryout
Bash
PWDEBUG=1 npx run tryout
Batch
set PWDEBUG=1 npx run tryout
Once you enter the command, the UI window also cognize as Inspector windows opens and shows the line is being fulfil. You can debug the test line by line using this window.
Points to Remember when applyPWDEBUG=1 flag:
- The browser launches in headed mode by default.
- There will be no default time-out.
- Playwright Inspector window is split into two parts: the upper part shows your code, and the lower part code shows the execution log.
- The Playwright provides two options either you can resume the script or you can tread over.
- If you need to pause the test at the desired line useawait page.pause ();in your book.
- If you add the await page.pause () playwright automatically opens the Inspector Window even though you have not set thePWDEBUG=1 flag.
Any time, if you don ’ t want to attach the Playwright inspector, change the PWDEBUG flag to 0 i.ePWDEBUG=0
Recording Scripts using Playwright Inspector Tool
Sometimes you might find it gainsay to understand how the locators feign flows utilise handwriting. Playwright Inspector Tool also cater a command calledcodegen, Popularly known as Playwright codegen that allows us to record the scripts automatically.
The codegen is like a recording creature. However, you can use this to generate complex scripts and later paste them inside our examination case.
From the terminal, you can enter the below bidding to record the tryout using Playwright Codegen Tool
npx playwright codegen & lt; webpage_url & gt;
Example:
npx playwright codegen browserstack.com
Once the above command is entered in the terminal, the Playwright examiner window launches. Therecordpush in the inspector window assist to start or stop the transcription at any coveted point. As the browser opensbaseURL,you can voyage the actions or workflow.
Upon completing the transcription, stop the transcription, Save/Copy the recorded script, and close the Playwright examiner window.
70 % of Playwright bugs fail only in CI
2. Playwright Debugging expend Browser Developer Tools
DevTools are part of the browser, which enables easy debug. While most browser hold this functionality, the shortcut key might differ from browser to browser. On your browser window correct click and choose inspect element. If you are using a chromium-based browser, you can also chooseCTRL +SHIFT + I or F12to open DevTools window.
Browser Developer tools are popularly cognise as DevTools. The browser developer tools are still accessible when running playwright tests.
Some of the actions that can be do expend Browser Developer Tools are:
- Inspect DOM Element
- Run commands in the browser console.
- Check console logs during performance
- Verify Network calls/requests in the Network tab
Apart from the activeness listed supra, any action that can be performed on a normal browser while work with webpage can be done using browser developer creature with Playwright.
Working with Playwright Object in Browser Developer Tools console (Chrome DevTools Console).
The Playwright allows you to highlight selectors in your browser console with the Playwright object. This is the most useful alternative, it facilitate debug locater and view the locators rendered during run clip.
To utilize this option, Playwright needs to be launched in debug style as explicate above (utilizePWDEBUG=1 flag). Once you launch the Playwright exam with debug mode, the Playwright Object is usable in the browser console.
There are many ways to highlight the locators using playwright objects, such as:
- playwright. $ (selector):Highlights the initiatory occurrence of the picker. This is equivalent to a page. $ usance in the script.
- playwright. $ $ (selector):Highlights all occurrences of the selector. This is tantamount to a page. $ $ utilization in the script.
- playwright.inspect (selector):Inspects the selector in the Elements panel.
- playwright.locator (selector):Highlights the first occurrent of the locater.
- playwright.clear ():Clears exist highlight.
- playwright.selector (element):Generates a selector that points to the element.
Example:
playwright. $ (`` a [href='/docs/intro '] '')
The above command in the browser console highlights the web element containing with locatora [href= & # 8217; /docs/intro & # 8217;]
3. Playwright Debugging apply Visual Studio Code
Playwright works good withVisual Studio Code. Suppose you are familiar with Java or C # and seek to debug using IDE breakpoints or the traditional debugging mode by setting and unsetting breakpoints. In that case, Playwright cater the like way of debugging pick.
To debug Playwright playscript using VS Code, follow the below steps.
Step 1: Navigate toVisual Studio Code Run Menu & gt; Click on Add Configuration
Step 2: Choose NodJS as an Environment
Step 3: The launch.jsonwill be created inside our labor folder mechanically. You can insure the file under
& lt; Project_Folder & gt; /.vscode/launch.json
Step 4: Editlaunch.jsonfile and participate the below code to it.
{`` version '': `` 0.2.0 '', `` configurations '': [{`` character '': `` pwa-node '', `` request '': `` launch '', `` name '': `` Launch Program '', `` skipFiles '': [`` & lt; node_internals & gt; / * * ''], `` programme '': `` $ {file} '', `` runtimeExecutable '': `` npm '', `` runtimeArgs '': [`` run-script '', `` test ''],}]}Step 5: Add trial command/value to script property inpackage.json.The package.jsonshould be located in the project beginning directory (Note: If package.json is not available in your Project root directory, so you can make one usenpm init command). Enter the below codification to the package.json and save the contour.
`` hand '': {`` test '': `` npx playwright test -- headed ''}Step 6: Run with Configuration in Visual Studio Code by following the below steps
- Set the breakpoint in your code with VSCode IDE
- Launch the test withRun (Menu) & gt; Start Debugging or F5
- The test starts with the debugger attached, the test execution should block when it hits your breakpoint.
4. Debugging Playwright Tests with Trace Viewer
Trace Vieweris another functionality that can be used while Playwright debugging. Trace Viewer is a GUI tool that shows the traces recorded during test execution. Trace watcher can be open using CLI or on the browser.
Recording Trace in Playwright
To record Trace, you need to configure it in theGlobose config file, and then follow these stairs:
Step 1:Create a Global Playwright Config File i.eplaywright.config.ts
Step 2: Place the playwright.config.tsunder the Project source directory
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
Step 3:Add the below code in it
// playwright.config.ts significance {PlaywrightTestConfig} from ' @ playwright/test '; const config: PlaywrightTestConfig = {use: {touch: 'on'},}; export default config;In the above code, thetrace option hasonvalue, besides, you can provide different value from the list of usable options fortrace
- & # 8216; off & # 8217;& # 8211; Do not record a trace.
- & # 8216; on & # 8217;& # 8211; Record a trace for each test.
- & # 8216; retain-on-failure & # 8217;& # 8211; Record a trace for each test, but remove it from successful test runs.
- & # 8216; on-first-retry & # 8217;& # 8211; Record a trace only when retrying a test for the first time.
Once you run the trial after configuring the shadow option to the global config file. Trace will be tape and stored in thetest-resultsdirectory.
Traces of your tests will be read action-wise. Each action contains
- activeness snapshot,
- activity log,
- source codification location,
- network log for this activity
Viewing Traces in Playwright
You can view the recorded Traces by following the below steps:
Step 1:Run/Execute your test
Step 2:Look for traces.zip inside your test-results leaflet
Step 3:From CLI you can recruit the path to trace file in the following formatting
npx playwright show-trace & lt; path_to_trace.zip_directory & gt; /trace.zip
For Example:
npx playwright show-trace test-results\tests-example-basic-test\trace.zip
Step 4:Exposed trace.zip from the browser (Optional). Navigate tohttps: //trace.playwright.dev/and then sweep and drop thetrace.zipfolder as seen below
5. Debug tests with Playwright Verbose Logging
Amidst the several debugging options provided by Playwright,Verbose loggingis another way to debug Playwright tests where the QA can see the tedious logs and canvas the scripts.
Enabling Verbose Logging in Playwright
The enabling of windy logging depends on which type of CLI/Terminal you use.
Enable Verbose Logging with Bash
DEBUG=pw: api npx playwright test
Enable Verbose Logging with Powershell
$ env: DEBUG= '' pw: api '' npx playwright test
Enable Verbose Logging with Batch
set DEBUG=pw: api npx playwright test
Once you enable the Verbose Log, Playwright ceaselessly feed the logs to the command line so you can see what & # 8217; s occur during the script execution.
6. Playwright Debugging in Headed Mode
By nonremittal, Playwright runs browser in headless mode where the browser operates in the background without a visible UI.
To run trial with the browser & # 8217; s UI visible (headed mode), you can set the headless option to false. Additionally, you can use the SlowMo choice to slow down the execution of each operation, making it leisurely to postdate the test steps in real-time.
Here ’ s how to run Playwright in head style with a delay between actions:
// Chromium, Firefox, or WebKit const {chromium} = require ('playwright '); (async () = & gt; {const browser = await chromium.launch ({headless: mistaken, // Run in head mode slowMo: 100 // Slow down execution by 100ms per operation}); // Your code for interacting with the browser move hither // Close the browser when done await browser.close ();}) ();With this setup, the browser will be visible during the test, and action will be slower, allowing you to note the behavior more easily and catch any issues as they occur.
7. Debug tests in UI mode
Playwright ’ s UI mode is a feature of the Playwright Test Runner. It makes it easy to debug tryout by cater a ocular interface to inspect and troubleshoot examination execution.
To start UI mode, run the following command in your terminal:
npx playwright test -- ui
This will open the Playwright Test Runner, where you can view and interact with your test files.
In UI mode, you ’ ll see a leaning of all your test files. You can:
- Run All Tests: Click the triangle icon in the sidebar to action all tests.
- Run a Single Test File:Hover over a file gens & amp; snap the triangle ikon next to it.
- Run Specific Tests: Expand a file to see individual tests & amp; click the triangle icon next to a test or group of tests.
Debugging Features in UI Mode
1. Timeline View
The timeline provides a optic overview of your test executing. Use the timeline to locate tough steps.
2. Actions Tab
The Actions tab gives elaborate information about each test step. Inspect details in the Actions tab, including locator and DOM changes.
3. DOM Inspection
Open and compare DOM snapshots to debug specific actions.
Debugging vs Tracing in Playwright
Debugging and tracing in Playwright solve different problems, even though they are frequently used interchangeably. Knowing when to use each determines how quickly a failure can be diagnosed, especially in CI and parallel execution.
| Aspect | Debugging | Tracing |
|---|---|---|
| Execution mode | Interactional and live | Recorded and replayable |
| Requires hesitate | Yes | No |
| Works in CI | Limited | Yes |
| Captures history | No | Yes |
| Handles flaky examination | Poorly | Effectively |
| Parallel execution | Difficult | Reliable |
| Best use example | Local development | CI and outre failures |
When to use debugging vs draw
Use debug when multiply an number locally and inspecting behavior step by step. Use tracing when failure are non-deterministic, environment-specific, or occur only under CI and parallel performance. Together, they form a complete Playwright debugging scheme.
Advanced Playwright Debugging Techniques
Modern Playwright failure usually descend into a few quotable buckets: network dubiety, time matter, missing artifact, secureness frame-up problem, or asseveration that fail without obvious reasons. The sections below explain how to debug each family without bank on repeated reruns.
Debugging Network, Timeouts, and Waits
Network and timing issues often coat as locator or navigation failure still when the real cause is a delayed request or wrong wait condition.
- Identify whether the failing step depends on an API call or async update
- Correlate failure timing with network action using traces
- Log failed API responses instead of only UI actions
- Distinguish locator, navigation, and assertion timeouts to pinpoint the effort
Replace difficult waits with postponement tied to real application signals
page.on ('response ', async (res) = & gt; {if (res.url () .includes ('/api/ ') & amp; & amp; res.status () & gt; = 400) {console.log (res.status (), res.url ());}});Analyzing Traces, Videos, and Screenshots
Debug artifacts cater the most reliable perceptivity for CI and flaky failures when local replication is not potential.
- Start with the trace timeline to find the last successful action
- Use DOM snapshots to verify element presence and profile
- Compare screenshots to detect overlays, loaders, or blocked UI
- Use video playback to identify animation or timing issues
- Correlate console erroneousness and mesh failure inside traces
Read More:
Debugging Fixtures and Setup Failures
Fixture issues frequently forbid tests from running at all, making failures harder to interpret.
- Check whether the test betray before executing the initiatory stride
- Validate fixture dependency order and explicit dependencies
- Watch for wrong worker-scoped fixture sharing mutable state
- Add log around use () to separate setup and teardown failures
- Avoid assertions inside fixtures, which hide root campaign
authedPage: async ({page}, use) = & gt; {console.log ('setup first '); look use (page); console.log ('teardown end ');};Debugging Assertion Failures
Assertion failures unremarkably bespeak timing gaps, stale locator, or wrong assumptions about UI state.
- Confirm the locator targets the intended element
- Differentiate between locator resolve failures and expectation mismatches
- Prefer user-visible assertions such as text, visibility, or URL
- Log minimal state like URL or key text when assertions fail
- Re-query locator after rerenders or route changeover
Read More:
await look (page.getByRole ('heading ', {name: 'Checkout '})) .toBeVisible (); console.log ('Current URL: ', page.url ());Common Challenges in Playwright Debugging
Debugging exam in Playwright can sometimes be tricky due to the complexity of modern web applications. Here are some mutual challenges:
- Unstable Tests (Flakiness):Tests fail intermittently due to timing issues, dynamic message, or network delays. Try usingwaitforstrategies and mock dynamic content and network responses to ensure a deterministic setup.
Read More:
- Incorrect Selectors: Selectors do not jibe the desired ingredient, especially when address with dynamic or complex DOMs. Use selectors likedata-testidor text content. You can so validate them via Playwright & # 8217; s inspector.
- Element Not Visible or Detached: Tests miscarry because elements are cover or removed from the DOM before interaction. Before interacting, use locator.waitFor () to expect for elements to be visible or stable in the DOM.
- Debugging Timeouts: Actions or assertions outgo the nonremittal timeout due to decelerate load or brio. Adjust action timeouts and usepage.waitForTimeout ()or address slow-loading elements withlocator.waitFor ().
- Complex Authentication Flows: Tests betray due to login mechanisms like CAPTCHA or multi-factor certification. In such cases, you can mock authentication or use browser context persistence.
- API and Network Issues: Tests break due to API failures or unexpected server responses.Use Playwright & # 8217; sroute and requestinterception features to stub network requests.
Read More:
- Environment Differences: Tests behave differently across environments (local, staging, production). Use environment-specific configuration files. Verify test setup with ordered test data and mocking when possible.
- Browser Compatibility: Tests fail or acquit differently on different browser. So, running your test on multiple browser is very important to validate compatibility.
Tips for Running and Debugging Tests in Playwright
Playwright is a powerful framework for end-to-end testing, offering tools and features to write true test and debug efficaciously.
Here are some best practices and tips to assist you get the most out of Playwright and overcome challenges.
1. Use Locators Effectively
- Playwright ’ s locators are make for reliability, with lineament like auto-waiting and retry capabilities.
- Locators are hard-and-fast, mean any operation imply a target DOM element will shed an error if more than one matching component exists. Hence, create locators uniquely identifying the mark element to avoid strictness topic and ensure dependable examination.
- Prefer user confront attributes, such as roles or schoolbook, over CSS or XPath selectors to make examination more lively.
Example:
// Good Practice page.getByRole ('button ', {name: 'Submit '}); // Avoid chooser tied to specific styles page.locator ('button.buttonIcon.submit-button ');- Use chaining and filtering to narrow down factor.
await page .getByRole ('listitem ') .filter ({hasText: 'Product 2 '}) .getByRole ('button ', {gens: 'Add to cart '}) .click ();Read More:
2. Generate Locators Automatically
- Use Playwright & # 8217; s test generator to create robust locators.
- Run npx playwright codegen & lt; url & gt; to open a browser and record interactions.
- You can inspect, modify, and copy locators straightaway in the Playwright Inspector or VS Code propagation.
3. Leverage Web-First Assertions
- Playwright & # 8217; s web-first affirmation wait for conditions to be met, ensuring stable tests.
// Recommended await expect (page.getByText ('Welcome ')) .toBeVisible (); // Avoid manual assertions without waiting expect (await page.getByText ('Welcome ') .isVisible ()) .toBe (true);4. Debugging Tips
Here are some debug tips you can follow:
Local Debugging:
- Use the VS Code extension to debug straightaway in your editor.
- Run examination in debug mode withnpx playwright trial & # 8211; debug.
- Add breakpoints to pause execution and inspect ingredient.
Debugging on CI:
- Use the Playwright vestige viewer to explore test failure.
- Configure traces in the Playwright config and enable them for retries.
npx playwright test -- trace on
Read More:
5. Optimize Tests for CI
- Run tests frequently on CI, ideally on each commit or attract request.
- Use Linux surroundings for cost efficiency.
- Download alone the browser you ask to relieve time and infinite:
npx playwright install chromium -- with-deps
6. Use Parallelism and Sharding
- Run tests in analogue to improve efficiency.
test.describe.configure ({mode: 'parallel '});- Shard test suites across multiple machine for bigger test sets:
npx playwright exam -- shard=1/3
7. Keep Playwright Updated
- Regularly update Playwright to ensure compatibility with the latest browser version.
npx playwright install @ modish
8. Test Across All Browsers
- Ensure your application works for all exploiter by testing across Chromium, Firefox, and WebKit.
- Configure projects in the Playwright config:
projects: [{name: 'chromium ', use: {... devices ['Desktop Chrome ']}}, {gens: 'firefox ', use: {... device ['Desktop Firefox ']}}, {name: 'webkit ', use: {... devices ['Desktop Safari ']}},];9. Use Playwright Tooling
- The VS Code extension ameliorate the development experience.
- The trace viewer helps analyze failures with elaborated log.
- UI Mode enable a time-travel-like experience for exploring and debugging tests.
Read More:
10. Lint and Optimize Your Code
Use TypeScript and linting with ESLint to catch mistake betimes.
Ensure asynchronous Playwright calls are properly awaited.
Example:
// ESLint prescript to prevent missing awaits@ typescript-eslint/no-floating-promises
Conclusion
While Playwright offers different debugging options for tests, it is up to you to choose the most suitable way to debug your tests to deliver a high-quality web application. No matter which debugging option you opt for, it is all-important to consider the existent user conditions which only possible by testing on real devices.
- Access 3500+ browser-device-OS combinations to integrate Playwright trial with.
- It can be integrated with CI/CD pipelines like, Travis CI,, Gitlab,, Bamboo, etc., and facilitate Agile squad run Parallel tests for a faster and more accurate testing experience.
Useful Resources for Playwright
Tool Comparisons:
On This Page
# Ask-and-Contributeabout this issue with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free