To write and run browser tests with Playwright, you write test scripts in JavaScript or TypeScript using Playwright’s API, then execute them with the Playwright Test runner via the command line. This article explains the core concepts, provides a step-by-step guide, and covers common pitfalls, so you can start automating browser checks quickly.
What Is Playwright?
Playwright is an open-source automation library developed by Microsoft for end-to-end testing of web applications. It supports all modern rendering engines: Chromium, Firefox, and WebKit. Unlike Selenium, which drives browsers through a WebDriver protocol, Playwright uses the Chrome DevTools Protocol and similar low-level APIs, giving it faster, more reliable control over browser actions. It works with JavaScript/TypeScript, Python, Java, and .NET, but the JavaScript version is the most widely used. Playwright can run tests in parallel, take screenshots, record videos, and emulate mobile devices, making it a popular choice for modern web development teams.
Setting Up Playwright
Before writing tests, you need to install Playwright and its browsers. The simplest way is to use npm (Node.js must be installed). Run the following commands in your project directory:
npm init -y– creates a package.json file.npm install -D @playwright/test– installs the test runner and library.npx playwright install– downloads the browser binaries (Chromium, Firefox, WebKit).
After installation, you can create a test file, typically named with a .spec.js or .test.js extension. For example, example.spec.js in a tests folder. Playwright’s test runner will automatically pick up files matching these patterns.
Writing Your First Test
A Playwright test is a function that uses the page fixture to interact with a browser page. Here’s a minimal example:
const { test, expect } = require('@playwright/test');
test('homepage has correct title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Example Domain');
});
In this test, page.goto() navigates to a URL, and expect(page).toHaveTitle() asserts the page title. Playwright’s assertions are auto-retrying; they wait for the condition to be met, which reduces flakiness. You can also interact with elements using locators: await page.locator('button').click(), fill inputs with await page.fill('#username', 'user'), and check visibility with await expect(page.locator('.success')).toBeVisible().
Running Tests
To run tests, use the command npx playwright test from your project root. This runs all test files in the default test directory. You can run a specific file by adding its path: npx playwright test tests/example.spec.js. To run a single test, use the -g flag with a test name pattern: npx playwright test -g "homepage". For debugging, use npx playwright test --debug which opens a browser with the Playwright inspector, allowing you to step through actions. To see the test in action with a visible browser, use npx playwright test --headed (default is headless). Playwright also supports parallel execution across files and workers; you can control this with the --workers flag.
Common Test Patterns
Real-world tests often need more than clicking and typing. Here are common patterns:
- Setup and teardown: Use
test.beforeEach()andtest.afterEach()to run code before/after each test, like navigating to a base URL or cleaning up data. - Fixtures: Define custom fixtures to share setup logic across tests, such as a logged-in page object.
- Page Objects: Encapsulate page interactions in classes to keep tests readable and maintainable.
- API requests: Use
requestfixture to make API calls for setup or validation, without opening a browser. - Visual comparisons: Use
expect(page).toHaveScreenshot()to compare screenshots for visual regression testing.
Configuration and Customization
Playwright Test uses a configuration file, playwright.config.js, to define test settings. You can specify browsers, viewport sizes, base URL, timeouts, and more. A basic config looks like:
const { defineConfig } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
timeout: 30000,
use: {
baseURL: 'https://example.com',
viewport: { width: 1280, height: 720 },
headless: true,
},
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
});
This setup runs tests in all three browsers. You can also set environment variables, use global setup files, and customize reporters (e.g., HTML, JSON, JUnit). The HTML reporter generates a visually appealing report with traces and screenshots on failure, which you can open with npx playwright show-report.
Common Problems and Solutions
Even with a robust tool, you’ll encounter issues. Here are frequent ones and how to fix them:
- Flaky tests due to timing: Avoid fixed waits like
page.waitForTimeout(). Use auto-retrying assertions andpage.waitForSelector()with state options. - Selectors not finding elements: Use user-facing attributes like
getByRole,getByLabel, orgetByTextinstead of brittle CSS paths. - Tests fail in headless mode but pass headed: Check for viewport differences, or animations that behave differently. Set a consistent viewport and disable animations in test config.
- Browser not installed: Run
npx playwright installagain, or install system dependencies withnpx playwright install-depson Linux. - Parallel tests interfering: Ensure each test uses isolated storage state (Playwright does this by default) and avoid shared global state on the server.
Comparison with Other Tools
Playwright is often compared to Selenium and Cypress. Selenium is older, supports many languages, and uses WebDriver, but is generally slower and more flaky. Cypress is developer-friendly with a rich dashboard, but it runs inside the browser, limiting cross-browser testing (it supports Chrome-family and Firefox, but not WebKit). Playwright offers better cross-browser support (including WebKit), faster execution via CDP, and built-in test runner with tracing. For new projects, Playwright is a strong choice due to its modern API and reliability.
Frequently Asked Questions
How do I run a single test file in Playwright?
Use npx playwright test tests/myfile.spec.js to run only that file. You can also use --grep to run tests matching a pattern in the test name.
Can I use Playwright with TypeScript?
Yes, Playwright has first-class TypeScript support. You can write tests in .ts files and run them without any extra configuration; the test runner compiles them automatically.
How do I take a screenshot in Playwright?
Use await page.screenshot({ path: 'screenshot.png' }) in your test. For automatic screenshots on failure, enable screenshot: 'only-on-failure' in the config’s use option.
Does Playwright work with CI/CD pipelines?
Yes, Playwright works well in CI. You can install browsers with npx playwright install and run tests with npx playwright test. Use the JUnit or HTML reporters to get results in CI dashboards.
How do I wait for a network response in Playwright?
Use page.waitForResponse() with a URL or predicate, e.g., await Promise.all([page.click('button'), page.waitForResponse('**/api/data')]).
What is the difference between page.click() and locator.click()?
page.click(selector) finds the first element matching the selector and clicks it. locator.click() is more precise because it targets a specific locator, which can be scoped to a parent element or a list item, reducing ambiguity.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Google Photos Backup Stuck? Fixes That Work
- Record Your Own Alarm Sound on Android
- Transfer Music from ZTE to iPhone: Full Guide
- Ways to Open Task Manager in Windows 10
- Convert Live Photos to Still Photos on iPhone
- Angel Investor vs Venture Capitalist: Key Differences