Skip to main content

从 Testing Library 迁移

迁移原则

¥Migration principles

本指南介绍从 DOM 测试库React 测试库Vue 测试库Svelte 测试库 迁移到 Playwright 的 实验组件测试

¥This guide describes migration to Playwright's Experimental Component Testing from DOM Testing Library, React Testing Library, Vue Testing Library and Svelte Testing Library.

注意

如果你在浏览器中使用 DOM 测试库(例如,使用 webpack 打包端到端测试),则可以直接切换到 Playwright Test。下面的示例侧重于组件测试,但对于端到端测试,你只需将 await mount 替换为 await page.goto('http://localhost:3000/') 即可打开被测页面。

¥If you use DOM Testing Library in the browser (for example, you bundle end-to-end tests with webpack), you can switch directly to Playwright Test. Examples below are focused on component tests, but for end-to-end test you just need to replace await mount with await page.goto('http://localhost:3000/') to open the page under test.

备忘单

¥Cheat Sheet

测试库Playwright
screenpagecomponent
querieslocators
异步助手assertions
用户事件actions
await user.click(screen.getByText('Click me'))await component.getByText('Click me').click()
await user.click(await screen.findByText('Click me'))await component.getByText('Click me').click()
await user.type(screen.getByLabelText('Password'), 'secret')await component.getByLabel('Password').fill('secret')
expect(screen.getByLabelText('Password')).toHaveValue('secret')await expect(component.getByLabel('Password')).toHaveValue('secret')
screen.getByRole('button', { pressed: true })component.getByRole('button', { pressed: true })
screen.getByLabelText('...')component.getByLabel('...')
screen.queryByPlaceholderText('...')component.getByPlaceholder('...')
screen.findByText('...')component.getByText('...')
screen.getByTestId('...')component.getByTestId('...')
render(<Component />);mount(<Component />);
const { unmount } = render(<Component />);const { unmount } = await mount(<Component />);
const { rerender } = render(<Component />);const { update } = await mount(<Component />);

示例

¥Example

测试库:

¥Testing Library:

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('sign in', async () => {
// Setup the page.
const user = userEvent.setup();
render(<SignInPage />);

// Perform actions.
await user.type(screen.getByLabelText('Username'), 'John');
await user.type(screen.getByLabelText('Password'), 'secret');
await user.click(screen.getByRole('button', { name: 'Sign in' }));

// Verify signed in state by waiting until "Welcome" message appears.
expect(await screen.findByText('Welcome, John')).toBeInTheDocument();
});

逐行迁移到 Playwright 测试:

¥Line-by-line migration to Playwright Test:

const { test, expect } = require('@playwright/experimental-ct-react'); // 1

test('sign in', async ({ mount }) => { // 2
// Setup the page.
const component = await mount(<SignInPage />); // 3

// Perform actions.
await component.getByLabel('Username').fill('John'); // 4
await component.getByLabel('Password').fill('secret');
await component.getByRole('button', { name: 'Sign in' }).click();

// Verify signed in state by waiting until "Welcome" message appears.
await expect(component.getByText('Welcome, John')).toBeVisible(); // 5
});

迁移亮点(请参阅 Playwright 测试代码片段中的内联注释):

¥Migration highlights (see inline comments in the Playwright Test code snippet):

  1. @playwright/experimental-ct-react(或 -vue、-svelte)导入所有内容以进行组件测试,或从 @playwright/test 导入以进行端到端测试。

    ¥Import everything from @playwright/experimental-ct-react (or -vue, -svelte) for component tests, or from @playwright/test for end-to-end tests.

  2. 测试函数被赋予一个与其他测试隔离的 page,以及在该页面中渲染组件的 mount。这是 Playwright 测试中的 有用的夹具 中的两个。

    ¥Test function is given a page that is isolated from other tests, and mount that renders a component in this page. These are two of the useful fixtures in Playwright Test.

  3. render 替换为返回 组件定位器mount

    ¥Replace render with mount that returns a component locator.

  4. 使用使用 locator.locator()page.locator() 创建的定位器来执行大部分操作。

    ¥Use locators created with locator.locator() or page.locator() to perform most of the actions.

  5. 使用 assertions 验证状态。

    ¥Use assertions to verify the state.

迁移查询

¥Migrating queries

所有查询(如 getBy...findBy...queryBy... 及其多元素对应项)均替换为 component.getBy... 定位器。定位器始终会在需要时自动等待并重试,因此你不必担心选择正确的方法。当你想做 列表操作 时,例如 断言文本列表,Playwright 自动执行多元素操作。

¥All queries like getBy..., findBy..., queryBy... and their multi-element counterparts are replaced with component.getBy... locators. Locators always auto-wait and retry when needed, so you don't have to worry about choosing the right method. When you want to do a list operation, e.g. assert a list of texts, Playwright automatically performs multi-element operations.

更换 waitFor

¥Replacing waitFor

Playwright 包括自动等待条件的 assertions,因此你通常不需要显式的 waitFor/waitForElementToBeRemoved 调用。

¥Playwright includes assertions that automatically wait for the condition, so you don't usually need an explicit waitFor/waitForElementToBeRemoved call.

// Testing Library
await waitFor(() => {
expect(getByText('the lion king')).toBeInTheDocument();
});
await waitForElementToBeRemoved(() => queryByText('the mummy'));

// Playwright
await expect(page.getByText('the lion king')).toBeVisible();
await expect(page.getByText('the mummy')).toBeHidden();

当找不到合适的断言时,请使用 expect.poll 代替。

¥When you cannot find a suitable assertion, use expect.poll instead.

await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}).toBe(200);

更换 within

¥Replacing within

你可以使用 locator.locator() 方法在另一个定位器中创建一个定位器。

¥You can create a locator inside another locator with locator.locator() method.

// Testing Library
const messages = document.getElementById('messages');
const helloMessage = within(messages).getByText('hello');

// Playwright
const messages = component.getByTestId('messages');
const helloMessage = messages.getByText('hello');

Playwright 测试超能力

¥Playwright Test Super Powers

一旦参加 Playwright 测试,你就会收获很多!

¥Once you're on Playwright Test, you get a lot!

  • 完全零配置 TypeScript 支持

    ¥Full zero-configuration TypeScript support

  • 在任何流行操作系统(Windows、macOS、Ubuntu)上跨所有 Web 引擎(Chrome、Firefox、Safari)运行测试

    ¥Run tests across all web engines (Chrome, Firefox, Safari) on any popular operating system (Windows, macOS, Ubuntu)

  • 全面支持多来源、(i)frames选项卡和上下文

    ¥Full support for multiple origins, (i)frames, tabs and contexts

  • 跨多个浏览器并行运行隔离测试

    ¥Run tests in isolation in parallel across multiple browsers

  • 内置测试 制品集合

    ¥Built-in test artifact collection

你还可以获得所有这些 ✨ 很棒的工具 ✨ 与 Playwright 测试打包在一起:

¥You also get all these ✨ awesome tools ✨ that come bundled with Playwright Test:

进一步阅读

¥Further Reading

了解有关 Playwright 测试运行程序的更多信息:

¥Learn more about Playwright Test runner: