Playwright with TypeScript
- Home
- Playwright with TypeScript
Using Playwright with TypeScript is one of the best modern stacks for writing robust, scalable, and type-safe end-to-end tests. TypeScript gives you better editor support, auto-completion, and early error detection.
Why Use Playwright + TypeScript?
Feature | Benefit |
---|---|
Modern testing engine | Fast, reliable, supports Chromium, Firefox, WebKit |
TypeScript support | Strong typing, autocompletion, cleaner code |
Tracing & debugging | Screenshots, video, trace viewer |
CI-ready setup | Ideal for GitHub Actions, Jenkins, GitLab, etc. |
1. Setup Project with TypeScript
npm init -y
npm install -D @playwright/test typescript ts-node
npx playwright install
npx tsc --init
Then initialize the Playwright project:
npx playwright test --init
This generates:
playwright.config.ts
Example tests in
tests/
tsconfig.json
2. Example Test (tests/login.spec.ts
)
import { test, expect } from '@playwright/test';
test('login successfully', 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. playwright.config.ts
(Optional Customization)
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
use: {
baseURL: 'https://example.com',
headless: true,
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
});
4. Run Tests
npx playwright test
Headed browser mode (for debugging):
npx playwright test --headed
To open the HTML report:
npx playwright show-report
5. Directory Structure
project-root/
├── tests/
│ └── login.spec.ts
├── playwright.config.ts
├── tsconfig.json
├── package.json
6. TypeScript Benefits in Playwright
Strongly-typed API (hover and autocomplete via
page.locator
,expect
, etc.)Compile-time checks for invalid locators or API usage
Clean integration with other tools (like ESLint, Prettier)