Writing your first end-to-end test with Playwright
Posted on
Are you ready to dive into modern web automation? Whether you're a developer or a tester, Playwright is one of the most powerful tools to write fast, reliable end-to-end (E2E) tests for modern web applications. In this guide, we'll walk you through writing your first E2E test with Playwright from setup to execution.
Let's get started!
What is End-to-End Testing?
End-to-End (E2E) testing simulates real user interactions in a browser. It tests your application from start to finish, including UI, APIs, and backend interactions, ensuring everything works together as expected.
Playwright makes E2E testing smooth by offering:
- Support for multiple browsers (Chromium, Firefox, WebKit)
- Auto-waiting for elements
- Fast parallel execution
- Rich features like network mocking, device emulation, and more
Step 1: Set Up Your Project
Before writing your first test, let's set up a Playwright testing environment.
Prerequisites
Make sure you have Node.js installed on your machine.
Initialize a New Project
npm init playwright@latest
This command will:
- Install Playwright and its dependencies
- Ask you a few setup questions (choose TypeScript or JavaScript based on your preference)
- Set up a sample project with example tests
Once done, your folder structure will look like this:
my-playwright-project/
├── tests/
│ └── example.spec.ts
├── playwright.config.ts
├── package.json
└── ...
Step 2: Create Your First Test
Let's create a simple test that:
- Opens a browser
- Navigates to a website (e.g., https://playwright.dev)
- Verifies the title of the page
Create a test file tests/firstTest.spec.ts
import { test, expect } from '@playwright/test'; test('Verify Playwright homepage title', async ({ page }) => { // Navigate to the Playwright website await page.goto('https://playwright.dev'); // Assert the title await expect(page).toHaveTitle(/Playwright/); });
Step 3: Run the Test
Use the Playwright test runner to execute your test:
npx playwright test
You'll see output like:
Running 1 test using 1 worker
✓ tests/firstTest.spec.ts:3:1 › Verify Playwright homepage title (3s)
1 passed (3s)
Congratulations, you've just written and run your first Playwright E2E test!