Language: JavaScript
Testing
Playwright was created by Microsoft to provide fast, reliable, and cross-browser automation for testing web applications. It aims to overcome the limitations of older tools like Selenium by providing automatic waiting, rich selectors, network interception, and built-in support for modern web features.
Playwright is a Node.js library for browser automation that enables reliable end-to-end testing across Chromium, Firefox, and WebKit with a single API. It supports modern web app features like single-page applications and multi-page flows.
npm install -D playwrightyarn add -D playwrightpnpm add -D playwrightPlaywright allows you to automate browser interactions for testing purposes, including navigation, clicking, typing, taking screenshots, capturing videos, and handling multiple pages or contexts. It provides APIs for synchronous-like control and automatic waiting.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();Launches a Chromium browser, opens a new page, navigates to a URL, and closes the browser.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.click('text=Sign in');
await page.fill('#username', 'myUser');
await page.fill('#password', 'myPass');
await page.click('#login');
await browser.close();
})();Demonstrates navigating through a login flow using selectors to click and type into form fields.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page1 = await context.newPage();
const page2 = await context.newPage();
await page1.goto('https://example.com');
await page2.goto('https://example.org');
await browser.close();
})();Shows creating multiple pages in the same browser context for parallel testing or multi-tab interactions.
await page.screenshot({ path: 'example.png' });Captures a screenshot of the current page for visual testing or debugging.
await page.route('**/api/**', route => route.fulfill({ body: JSON.stringify({ data: 'mocked' }) }));Mocks API responses by intercepting network requests matching a pattern.
const { firefox, webkit } = require('playwright');
// Launch Firefox or WebKit with the same API as ChromiumPlaywright allows cross-browser testing using a consistent API for Chromium, Firefox, and WebKit.
Use page locators for stable element selection instead of brittle selectors.
Leverage automatic waiting to reduce flakiness in tests.
Run tests in headless mode in CI/CD pipelines for speed.
Use browser contexts to isolate tests and avoid state sharing.
Take screenshots or videos for debugging failed tests.