Playwright UI Testing: A Beginner’s Step-by-Step Guide
This guide walks you through setting up automated UI testing from scratch using Playwright, a modern browser automation tool. You’ll learn how to install Playwright, write your first test, run it, and integrate it into your workflow. By the end, you’ll have a working test suite that can verify your web application’s functionality across multiple browsers.
What You’ll Need
- Node.js (version 16 or later) installed on your machine. You can download it from the official Node.js website.
- A code editor (like VS Code, Sublime Text, or any other you prefer).
- Basic familiarity with JavaScript or TypeScript syntax (Playwright supports both).
- A web application to test (it can be a local development server or a public URL).
Step-by-Step
- Initialize a new Node.js project
Open your terminal, create a new folder for your test project, and navigate into it. Runnpm init -yto create apackage.jsonfile with default settings. - Install Playwright
Runnpm install -D @playwright/testto install Playwright’s test runner. Then runnpx playwright installto download the browser binaries (Chromium, Firefox, WebKit). This may take a few minutes depending on your internet speed. - Create a test file
Create a new folder calledtestsin your project root. Inside it, create a file namedexample.spec.js. This is where you’ll write your first test. - Write your first test
Open the file and add the following code:const { test, expect } = require('@playwright/test'); test('Page title is correct', async ({ page }) => { await page.goto('https://example.com'); await expect(page).toHaveTitle('Example Domain'); });This test navigates to a URL and checks that the page title matches the expected value.
- Run the test
In the terminal, runnpx playwright test. Playwright will run the test in headless mode (no browser window) and show you the results in the terminal. If the test passes, you’ll see a green checkmark. - Run tests with a visible browser
To see what’s happening during the test, runnpx playwright test --headed. This opens a browser window so you can watch the test execute. - Add more assertions
Playwright provides many assertions. For example, to check that a button is visible and clickable, you can use:await expect(page.locator('button.submit')).toBeVisible(); await page.click('button.submit');Explore the Playwright API docs to find more.
- Use fixtures for setup
If you need to log in before each test, you can use abeforeEachhook. For example:test.beforeEach(async ({ page }) => { await page.goto('https://example.com/login'); await page.fill('#username', 'testuser'); await page.fill('#password', 'password'); await page.click('button[type="submit"]'); });This runs before each test in the file.
- Run tests in multiple browsers
By default, Playwright runs tests in Chromium. To run in Firefox and WebKit too, create aplaywright.config.jsfile at the project root with:module.exports = { projects: [ { name: 'chromium', use: { browserName: 'chromium' } }, { name: 'firefox', use: { browserName: 'firefox' } }, { name: 'webkit', use: { browserName: 'webkit' } }, ], };Then run
npx playwright testagain. It will run your tests in all three browsers. - Generate a test report
After running tests, Playwright generates an HTML report by default. To view it, runnpx playwright show-reportafter the test run. This opens a detailed report in your browser showing pass/fail status, test duration, and screenshots on failure.
Common Mistakes
- Not using proper selectors – Using fragile selectors like
#main-content > div > buttoncan break when the DOM changes. PrefergetByRole,getByText, or data-testid attributes. - Ignoring waits – Playwright auto-waits for elements to be actionable, but if you use
page.waitForTimeout()excessively, it slows down tests and can cause flakiness. Use explicit waits likeexpect(locator).toBeVisible()instead. - Running tests in parallel without isolation – If tests share state (like a database), running them in parallel can cause conflicts. Use Playwright’s fixtures to set up and tear down data per test.
- Not using the test runner – Writing raw scripts with
playwright.chromium.launch()instead of using the test runner misses out on features like fixtures, parallelism, and reporting.
Tips
- Use
data-testidattributes in your app’s HTML to make selectors stable and independent of styling or structure. - Take advantage of Playwright’s trace viewer by adding
trace: 'on-first-retry'in your config. It records a full trace of the test, including network requests and console logs, which is invaluable for debugging. - Use
test.describeto group related tests and share setup/teardown logic. - Run a single test with
npx playwright test --grep "test name"to save time during development. - Keep your tests independent – each test should be able to run alone and in any order. Use
test.beforeEachto reset state.
Troubleshooting
- Tests fail with “Error: browserType.launch: Executable doesn’t exist” – This means the browser binaries are not installed. Run
npx playwright installagain, and ensure you have internet access. - Tests are slow – Check if you’re using
page.waitForTimeout()excessively. Also, consider running tests in parallel by settingfullyParallel: truein your config (default in newer versions). - Element not found – If a selector fails, use
page.locator('your-selector').count()to see how many elements match. Also, try usingpage.pause()to open the Playwright Inspector and debug interactively. - Test passes locally but fails in CI – This often happens due to missing system dependencies for browsers in the CI environment. Run
npx playwright install-depson your CI machine (Linux) to install required libraries. - Cannot run on Windows with WebKit – Playwright’s WebKit on Windows may have limitations. Use a Linux or macOS environment for full WebKit support, or rely on Chromium and Firefox.
Frequently Asked Questions
Do I need to write tests in JavaScript?
No, Playwright supports TypeScript out of the box. You can write tests in .spec.ts files and use type checking for better code quality.
Can I test a website that requires authentication?
Yes. You can either log in within a beforeEach hook, or use Playwright’s storage state feature to save cookies and reuse them across tests.
How do I take screenshots on failure?
By default, Playwright captures a screenshot when a test fails. You can also manually capture screenshots using await page.screenshot({ path: 'screenshot.png' }).
Can I run tests on a real mobile device?
Playwright can emulate mobile devices by setting the viewport and user agent. For real device testing, you’d need a separate cloud service, but for most UI testing, emulation is sufficient.
How do I run a single test file?
Use npx playwright test tests/example.spec.js to run a specific file. You can also use --grep to filter by test name.
Is Playwright free to use?
Yes, Playwright is open-source and free. You only need to pay if you use a cloud service for parallel execution, but you can run tests locally for free.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.