Node.js Playwright
Node.js Testing with Playwright
Playwright is a Node.js library for testing web apps in real browsers.
Unit tests, like the ones in the Test Runner chapter, check one function at a time.
A Playwright test opens your app in Chromium, Firefox or WebKit, clicks and types like a user, and checks what the page shows.
This kind of test is called an end-to-end test, because it tests the whole app, from the browser to the server.
Install Playwright
Create a new Playwright project in an empty folder:
Example
npm init playwright@latest
The command asks a few questions, installs @playwright/test, downloads the browsers and creates a config file and a tests folder.
To add Playwright to an existing Node.js project instead:
Example
npm install --save-dev @playwright/test
npx playwright install
Write a Test
This test opens a todo list app, adds a todo and checks the result:
Example
tests/todo.spec.js
import { test, expect } from '@playwright/test';
test('can add a todo', async ({ page }) => {
await page.goto('https://www.w3schools.com/playwright/practice/todo.html');
await page.getByPlaceholder('What needs to be done?').fill('Learn Playwright');
await page.getByRole('button', { name: 'Add' }).click();
await expect(page.getByTestId('todo-count')).toHaveText('1 item left');
});
Every Playwright action is asynchronous, so each line starts with await.
The page is a fresh browser tab that Playwright gives each test.
Run the Test
Example
npx playwright test
Output:
Running 1 test using 1 worker
[1/1] [chromium] › tests/todo.spec.js:3:1 › can add a todo
1 passed (3.9s)
This output comes from a config with only the Chromium browser.
The config that npm init playwright creates also runs Firefox and WebKit, so you will see 3 tests: one per browser.
The browser runs in the background, without a visible window, by default.
Add --headed to see the browser window while the test runs.
Learn More
Our Playwright Tutorial covers everything you need to test a real app:
- Locators: finding elements the way users see them
- Assertions: checks that wait for the page
- Trace Viewer: seeing exactly what happened in a failed test
- API Testing: testing your Node.js API without a browser
- Run in CI: running the tests on every push