使用 Playwright 进行端到端测试
设置端到端测试,模拟用户在整个应用流程中的交互。
使用 Playwright 进行端到端测试 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is End-to-End Testing?
End-to-End (E2E) testing simulates a real user's journey through your application, from start to finish. It tests the entire stack: frontend, backend, and database.
Think of it as a robot user interacting with your app in a browser. This ensures all parts of your system work together as expected, catching issues that unit or integration tests might miss.
Why Playwright for E2E?
Playwright is a powerful open-source tool by Microsoft designed for reliable E2E testing. It offers several key advantages:
- Cross-browser: Tests Chromium, Firefox, and WebKit (Safari).
- Auto-wait: Automatically waits for elements to be ready, reducing flakiness.
- Robust actions: Simulates real user interactions like clicks, fills, and key presses.
- Fast & parallel: Can run tests across multiple browsers simultaneously.
Setting Up Playwright
To get started, you'll need to install Playwright in your Next.js project. This command sets up Playwright and downloads necessary browser binaries:
npm init playwright@latest
This will guide you through setting up a basic configuration file (playwright.config.ts) and an example test. Remember to have your Next.js application running (e.g., npm run dev) when running E2E tests!
Your First Playwright Test
Let's write a simple test to navigate to a page and check its title. Playwright tests are typically written in JavaScript or TypeScript.
This example assumes your Next.js app is running on http://localhost:3000.
import { test, expect } from '@playwright/test';
test('homepage has expected title', async ({ page }) => {
await page.goto('http://localhost:3000/');
// Check if the page title contains 'Next.js App'
await expect(page).toHaveTitle(/Next.js App/);
});Interacting with Elements
Playwright provides powerful locators to find elements on the page. You can interact with these elements by filling input fields, clicking buttons, and more.
Common locators include getByRole(), getByText(), getByLabel(), and locator() for CSS selectors.
import { test, expect } from '@playwright/test';
test('fill and submit a contact form', async ({ page }) => {
await page.goto('http://localhost:3000/contact');
// Fill input fields by label or placeholder
await page.getByLabel('Your Name').fill('Alice');
await page.getByPlaceholder('email@example.com').fill('alice@example.com');
// Click the submit button
await page.getByRole('button', { name: 'Send Message' }).click();
// Assert that a success message appears
await expect(page.getByText('Message sent successfully!')).toBeVisible();
});Assertions and Auto-Waiting
Playwright's expect API is used to make assertions about the state of your application. A key feature is auto-waiting, where Playwright automatically waits for elements to become visible, enabled, or stable before performing an action or assertion.
This significantly reduces the need for manual waits, making your tests more robust and less prone to flakiness.
import { test, expect } from '@playwright/test';
test('check item count', async ({ page }) => {
await page.goto('http://localhost:3000/products');
// Playwright waits for the list to render
const productList = page.locator('.product-item');
await expect(productList).toHaveCount(5);
// Click a filter button
await page.getByRole('button', { name: 'Filter by Category A' }).click();
// Playwright waits for the list to update after filtering
await expect(productList).toHaveCount(2);
});Testing a Full User Flow
Let's simulate a more complex user journey: a user logging in, navigating to a dashboard, and verifying content. This demonstrates how E2E tests cover multiple pages and interactions.
Ensure your Next.js application has a login page and a dashboard for this test to pass.
import { test, expect } from '@playwright/test';
test('user can log in and view dashboard', async ({ page }) => {
await page.goto('http://localhost:3000/login');
// Fill login form
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('securepassword');
await page.getByRole('button', { name: 'Log In' }).click();
// Wait for navigation to the dashboard and verify content
await page.waitForURL('http://localhost:3000/dashboard');
await expect(page.getByRole('heading', { name: 'Welcome, testuser!' })).toBeVisible();
await expect(page.getByText('Your recent activity')).toBeVisible();
});Running Tests & Reporting
After writing your tests, you can run them from your terminal. Playwright provides a powerful test runner and various reporting options:
- Run all tests:
npx playwright test - Run specific test file:
npx playwright test example.spec.js - Run tests in headed mode (browser visible):
npx playwright test --headed - HTML Reporter: After tests run, open
playwright-report/index.htmlfor a detailed, interactive report.
Best Practices for E2E Tests
To write effective and maintainable E2E tests:
- Target user-facing elements: Use locators that reflect how a user sees the page (e.g.,
getByRole,getByText). - Use
data-testidattributes: For elements without clear text or roles, adddata-testidattributes for robust selection. - Keep tests independent: Each test should set up its own state and not rely on previous tests.
- Balance test types: E2E tests are slower; use them for critical user flows, and rely on unit/integration tests for smaller components.
Playwright Test Concepts
Which of the following are key benefits or features of Playwright for End-to-End testing?
Recap: E2E with Playwright
We've explored End-to-End testing and how Playwright helps you simulate real user interactions across your entire Next.js application.
You learned to set up Playwright, write tests that navigate, interact with elements, and assert outcomes. With its auto-waiting capabilities and cross-browser support, Playwright is a powerful tool for ensuring the reliability of your fullstack applications.
常见问题解答
「使用 Playwright 进行端到端测试」课时是免费的吗?
是的 — 「使用 Playwright 进行端到端测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「使用 Playwright 进行端到端测试」这节课中我会学到什么?
设置端到端测试,模拟用户在整个应用流程中的交互。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 Playwright 进行端到端测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 单元测试与集成测试
- 使用 Playwright 进行端到端测试
- 单体仓库与微前端
- 模拟与测试服务器组件