Skip to main content

從 Testing Library 遷移

遷移原則

這個指南描述了從 DOM Testing LibraryReact Testing LibraryVue Testing LibrarySvelte Testing Library 遷移到 Playwright 的 Experimental Component Testing

note

如果你在瀏覽器中使用 DOM Testing Library(例如,你使用 webpack 打包端到端測試),你可以直接切換到 Playwright Test。以下範例專注於元件測試,但對於端到端測試,你只需將 await mount 替換為 await page.goto('http://localhost:3000/') 來打開測試頁面。

Cheat Sheet

Testing LibraryPlaywright
screenpagecomponent
querieslocators
async helpersassertions
user eventsactions
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 />);

範例

測試函式庫:

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 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 Test 程式碼片段中的內嵌註釋):

  1. @playwright/experimental-ct-react(或 -vue, -svelte)匯入所有內容以進行元件測試,或從 @playwright/test 進行端到端測試。
  2. 測試函式會給予一個與其他測試隔離的 page,以及在此頁面中渲染元件的 mount。這些是 Playwright Test 中的兩個有用的 fixtures
  3. render 替換為 mount,它會返回一個元件定位器
  4. 使用 locator.locator()page.locator() 建立的定位器來執行大多數操作。
  5. 使用斷言來驗證狀態。

遷移查詢

所有像 getBy...findBy...queryBy... 以及它們的多元素對應項都被替換為 component.getBy... 定位器。定位器總是自動等待並在需要時重試,因此你不必擔心選擇正確的方法。當你想要進行列表操作時,例如斷言一個文本列表,Playwright 會自動執行多元素操作。

替換 waitFor

Playwright 包含斷言會自動等待條件成立,所以通常不需要明確呼叫 waitFor/waitForElementToBeRemoved

// 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

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

替換 within

你可以使用 locator.locator() 方法在另一個定位器內建立定位器。

// 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 Test 超能力

一旦你使用 Playwright 測試,你會獲得很多!

  • 完整的零配置 TypeScript 支援
  • 所有網頁引擎(Chrome, Firefox, Safari)上執行測試,適用於任何流行的作業系統(Windows, macOS, Ubuntu)
  • 完整支援多個來源,(i)frames, 分頁和上下文
  • 在多個瀏覽器中平行獨立執行測試
  • 內建測試 artifact collection

你還會獲得所有這些 ✨ 很棒的工具 ✨,這些工具與 Playwright Test 一起捆綁提供:

延伸閱讀

了解更多關於 Playwright 測試執行器: