Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@playwright/test
Advanced tools
The @playwright/test npm package is a framework for end-to-end testing that allows developers to automate browser interactions for testing web applications. It supports multiple browsers, provides a rich set of APIs for navigation, interaction, and assertions, and offers features like test parallelization, fixtures, and snapshot testing.
Browser Automation
Automate browser actions such as navigating to a URL, interacting with page elements, and validating page properties.
const { test, expect } = require('@playwright/test');
test('basic test', async ({ page }) => {
await page.goto('https://example.com');
const title = await page.title();
expect(title).toBe('Example Domain');
});
Cross-Browser Testing
Run tests across multiple browsers like Chromium, Firefox, and WebKit.
const { test } = require('@playwright/test');
test.describe.configure({ browsers: ['chromium', 'firefox', 'webkit'] });
test('cross-browser test', async ({ page }) => {
await page.goto('https://example.com');
// Perform cross-browser checks
});
Mobile Emulation
Emulate mobile devices to test responsive designs and touch interactions.
const { devices, test } = require('@playwright/test');
const iPhone11 = devices['iPhone 11 Pro'];
test('mobile emulation test', async ({ browser }) => {
const context = await browser.newContext({
...iPhone11,
});
const page = await context.newPage();
await page.goto('https://example.com');
// Perform actions in the emulated mobile environment
});
Visual Regression Testing
Capture screenshots and compare them against known good snapshots to detect visual regressions.
const { test, expect } = require('@playwright/test');
test('visual test', async ({ page }) => {
await page.goto('https://example.com');
expect(await page.screenshot()).toMatchSnapshot('homepage.png');
});
Test Fixtures
Create reusable test setup and teardown logic with fixtures.
const { test } = require('@playwright/test');
test('use fixture', async ({ myFixture }) => {
// Use the fixture in the test
});
test.extend({
myFixture: async ({}, use) => {
// Set up the fixture
await use('some value');
// Clean up the fixture
},
});
Cypress is a popular end-to-end testing framework similar to Playwright. It offers a rich interactive test runner and has a focus on ease of use. Unlike Playwright, Cypress only supports testing in a Chromium-based browser, which can be a limitation for cross-browser testing.
Selenium WebDriver is one of the oldest and most widely used browser automation tools. It supports multiple programming languages and browsers. Compared to Playwright, Selenium tests tend to be slower and can be more flaky due to reliance on the WebDriver protocol.
Puppeteer is a Node library developed by the Chrome DevTools team. It provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Playwright is considered a successor to Puppeteer and extends its capabilities by supporting more browsers and additional features.
Nightwatch.js is an automated testing framework for web applications and websites, using the W3C WebDriver API. It is easy to use and set up. Compared to Playwright, Nightwatch may have less advanced features and browser support but is still a solid choice for many testing scenarios.
TestCafe is a node.js tool for automating end-to-end web testing. It is known for its ease of setup and use, and it does not require WebDriver. Unlike Playwright, TestCafe runs tests written in JavaScript or TypeScript directly in the browser which can be both an advantage and a limitation depending on the context.
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.
Linux | macOS | Windows | |
---|---|---|---|
Chromium 129.0.6668.29 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
WebKit 18.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Firefox 130.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all browsers on all platforms. Check out system requirements for details.
Looking for Playwright for Python, .NET, or Java?
Playwright has its own test runner for end-to-end tests, we call it Playwright Test.
The easiest way to get started with Playwright Test is to run the init command.
# Run from your project's root directory
npm init playwright@latest
# Or create a new project
npm init playwright@latest new-project
This will create a configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts. You can now jump directly to writing assertions section.
Add dependency and install browsers.
npm i -D @playwright/test
# install supported browsers
npx playwright install
You can optionally install only selected browsers, see install browsers for more details. Or you can install no browsers at all and use existing browser channels.
Auto-wait. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts - a primary cause of flaky tests.
Web-first assertions. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met.
Tracing. Configure test retry strategy, capture execution trace, videos and screenshots to eliminate flakes.
Browsers run web content belonging to different origins in different processes. Playwright is aligned with the architecture of the modern browsers and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations.
Multiple everything. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test.
Trusted events. Hover elements, interact with dynamic controls and produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user.
Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly.
Browser contexts. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds.
Log in once. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests.
Codegen. Generate tests by recording your actions. Save them into any language.
Playwright inspector. Inspect page, generate selectors, step through the test execution, see click points and explore execution logs.
Trace Viewer. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source and many more.
Looking for Playwright for TypeScript, JavaScript, Python, .NET, or Java?
To learn how to run these Playwright Test examples, check out our getting started docs.
This code snippet navigates to Playwright homepage and saves a screenshot.
import { test } from '@playwright/test';
test('Page Screenshot', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.screenshot({ path: `example.png` });
});
This snippet emulates Mobile Safari on a device at given geolocation, navigates to maps.google.com, performs the action and takes a screenshot.
import { test, devices } from '@playwright/test';
test.use({
...devices['iPhone 13 Pro'],
locale: 'en-US',
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: ['geolocation'],
})
test('Mobile and geolocation', async ({ page }) => {
await page.goto('https://maps.google.com');
await page.getByText('Your location').click();
await page.waitForRequest(/.*preview\/pwa/);
await page.screenshot({ path: 'colosseum-iphone.png' });
});
This code snippet navigates to example.com, and executes a script in the page context.
import { test } from '@playwright/test';
test('Evaluate in browser context', async ({ page }) => {
await page.goto('https://www.example.com/');
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
}
});
console.log(dimensions);
});
This code snippet sets up request routing for a page to log all network requests.
import { test } from '@playwright/test';
test('Intercept network requests', async ({ page }) => {
// Log and continue all network requests
await page.route('**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://todomvc.com');
});
FAQs
A high-level API to automate web browsers
The npm package @playwright/test receives a total of 5,081,442 weekly downloads. As such, @playwright/test popularity was classified as popular.
We found that @playwright/test demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.