- Tác giả
- Name
- Nguyễn Đức Xinh
- Ngày xuất bản
- Ngày xuất bản
Complete Guide to Setting Up and Deploying Playwright Project with TypeScript from A-Z
Introduction to Playwright and TypeScript
Playwright is a powerful end-to-end testing framework developed by Microsoft, allowing automated testing across different browsers such as Chromium, Firefox, and WebKit with a unified API. Combined with TypeScript, Playwright becomes a robust testing tool with type-checking capabilities, making the code safer and more maintainable.
In this article, we will explore how to install and configure a Playwright project with TypeScript from scratch. We'll go through detailed steps, including installing necessary dependencies, creating project structure, writing basic tests, and running initial test cases.
Why Choose Playwright with TypeScript?
- Cross-browser testing: Playwright fully supports major browsers (Chromium, Firefox, WebKit) with a unified API.
- Auto-waiting: Automatically waits for elements to be ready for interaction.
- Popular JavaScript: Familiar language for most developers, reducing learning and implementation time.
- Type safety: TypeScript helps detect errors during development.
- Network interception: Ability to intercept and modify network requests.
- Mobile emulation: Support for testing on mobile devices through device emulation.
- Parallel execution: Ability to run tests concurrently to optimize time.
System Requirements
Before starting, ensure your computer meets the following requirements:
- Node.js (version 18 or higher)
- npm, pnpm, or yarn (package manager)
- Code editor like Visual Studio Code (recommended)
To check your installed Node.js version:
node -v
# v24.1.0
To check your installed npm/pnpm version:
npm -v
# 11.4.1
pnpm -v
Installing Playwright Project with TypeScript
Step 1: Create a New Project
First, we need to create a new directory for the project and initialize a Node.js project:
mkdir playwright-automation-ts
cd playwright-automation-ts
Step 2: Install Playwright and TypeScript
Install Playwright along with necessary TypeScript dependencies:
npm init playwright@latest
During the installation, you'll be asked several configuration questions. Choose the appropriate options:
- Do you want to use TypeScript or JavaScript? » TypeScript
- Where to put your end-to-end tests? » tests
- Add a GitHub Actions workflow? » Yes/No (depending on your needs)
- Install Playwright browsers (can be done manually via 'npx playwright install')? » Yes
The installation process will create an initial project structure with necessary configuration files.
Step 3: Check Project Structure
After installation is complete, your project structure will look like this:
playwright-automation-ts/
├── node_modules/
├── package.json
├── package-lock.json
├── playwright.config.ts
├── tests/
│ └── example.spec.ts
├── tests-examples/
│ └── demo-todo-app.spec.ts
└── tsconfig.json
./tests/example.spec.ts
: This is a sample end-to-end test file../tests-examples/demo-todo-app.spec.ts
- This is a sample end-to-end test file for the Todo application.
Step 4: Understanding Configuration Files
playwright.config.ts
File
This file contains the main configuration for Playwright, including browser settings, timeouts, and other options:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
});
The playwright.config.ts
configuration file will be automatically created in the project root directory. You can customize settings such as:
- Timeouts: Default wait times for actions and assertions
- projects: Choose default browsers for running tests (Chromium, Firefox, WebKit)
- testDir: Directory containing test cases
- reporter: Choose report format (HTML, JSON, etc.)
- use: Common settings for all tests, such as viewport, user agent, etc.
- etc.
Writing Your First Test with Playwright and TypeScript
Now let's write our first test case using Playwright TypeScript. For this, we'll use Njndex Dummy Demo, and the test will run on our local machine.
To understand how Playwright works, we'll write a simple test to check the homepage of Njndex Dummy Demo.
Create a New Test File
In the tests
directory, create a new file named homepage.spec.ts
:
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
// 1. Navigate to the page
await page.goto('https://dummy-demo-njndex.web.app');
// 2. Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Demo Dummy/);
// 3. Expect a title "to be" a specific string.
await expect(page).toHaveTitle("Home | IT Demo Dummy");
});
test('Can navigate to the Todo list page', async ({ page }) => {
// 1. Navigate to the page
await page.goto('https://dummy-demo-njndex.web.app/');
// 2. Click the "Todo List Demo" link
await page.getByTestId('feature-link-todo_list').click();
// 3. Verify URL change
await expect(page).toHaveURL(/todo-list/);
// 4. Verify page content
await expect(page).toHaveTitle(/Todo List | IT Demo Dummy/);
await expect(page.getByRole('heading', { name: 'Todo List' })).toBeVisible();
});
Running Tests
To run the tests, use the command:
npx playwright test
To run tests with UI mode:
npx playwright test --ui
To view test results, run:
npx playwright show-report
Basic Playwright Commands
Here are some basic Playwright commands you can use:
To run tests on a specific browser:
npx playwright test --project=chromium
To run tests with a specific file:
npx playwright test example
To automatically generate tests with Playwright Codegen, use:
npx playwright codegen https://dummy-demo-njndex.web.app
This is a great feature of Playwright that helps you automatically generate test code by recording your browser actions. You can choose the output language as JavaScript or TypeScript.
Conclusion
In this article, we've learned about installing and configuring a Playwright project with TypeScript. We've gone through the basic steps, including installing dependencies, creating project structure, and writing our first test case.
In the next article, we'll explore advanced topics such as:
- Page Object Model (POM)
- Fixtures and their usage
- Advanced Playwright configuration
- API testing with Playwright
- Screenshot and Video Recording