Playwright with JavaScript
- Home
- Playwright with JavaScript
Playwright with JavaScript is a modern, powerful automation framework created by Microsoft that supports fast, reliable, and cross-browser testing for web applications.
It supports:
Chromium (Chrome, Edge)
Firefox
WebKit (Safari)
Why Use Playwright?
Feature | Benefit |
---|---|
Cross-browser support | Test in Chromium, Firefox, WebKit |
Fast execution | Parallelism and browser context isolation |
Auto-waiting | Waits for elements and network by default |
Screenshots/videos | Easy debugging with trace viewer |
Headless & headed modes | Run tests visibly or in CI pipelines |
1. Install Playwright
npm init -y
npm install -D @playwright/test
npx playwright install
This installs browsers too.
2. Create a Test File (tests/login.spec.js
)
// @ts-check
const { test, expect } = require('@playwright/test');
test('successful login', async ({ page }) => {
await page.goto('https://example.com/login');
await page.fill('#username', 'testuser');
await page.fill('#password', 'testpass');
await page.click('#login');
await expect(page.locator('#logout')).toBeVisible();
});
3. Configure Playwright (playwright.config.js
)
// playwright.config.js
module.exports = {
testDir: './tests',
retries: 1,
use: {
headless: true,
screenshot: 'only-on-failure',
video: 'retain-on-failure',
baseURL: 'https://example.com',
},
};
4. Run Tests
npx playwright test
Run a specific test file:
npx playwright test tests/login.spec.js
Headed mode (for visual debug):
npx playwright test --headed
5. Debugging Tips
Run with inspector:
npx playwright test --debug
Use
.trace()
to record trace logs for failed tests.
6. Additional Features
test.describe()
for groupingtest.beforeEach()
for setuppage.locator()
for more reliable element handlingTracing and reporting:
npx playwright show-report