跳到主要内容

组件(实验性)

介绍

Playwright Test 现在可以测试你的组件了。

示例

下面是一个典型的组件测试示例

test('event should work', async ({ mount }) => {
let clicked = false;

// Mount a component. Returns locator pointing to the component.
const component = await mount(
<Button title="Submit" onClick={() => { clicked = true }}></Button>
);

// As with any Playwright test, assert locator text.
await expect(component).toContainText('Submit');

// Perform locator click. This will trigger the event.
await component.click();

// Assert that respective events have been fired.
expect(clicked).toBeTruthy();
});

如何开始

将 Playwright Test 添加到现有项目很容易。以下是为 React、Vue 或 Svelte 项目启用 Playwright Test 的步骤。

步骤 1:为你相应的框架安装 Playwright 组件测试

npm init playwright@latest -- --ct

此步骤会在你的工作区创建几个文件

playwright/index.html
<html lang="en">
<body>
<div id="root"></div>
<script type="module" src="./index.ts"></script>
</body>
</html>

此文件定义了一个 HTML 文件,该文件将用于在测试期间渲染组件。它必须包含一个 id="root" 的元素,组件将挂载在该元素下。它还必须链接名为 playwright/index.{js,ts,jsx,tsx} 的脚本。

你可以使用此脚本在组件挂载的页面中包含样式表、应用主题和注入代码。它可以是 .js.ts.jsx.tsx 文件。

playwright/index.ts
// Apply theme here, add anything your component needs at runtime here.

步骤 2. 创建测试文件 src/App.spec.{ts,tsx}

app.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import App from './App';

test('should work', async ({ mount }) => {
const component = await mount(<App />);
await expect(component).toContainText('Learn React');
});

步骤 3. 运行测试

你可以使用 VS Code 扩展 或命令行来运行测试。

npm run test-ct

进一步阅读:配置报告、浏览器、跟踪

参考 Playwright 配置 来配置你的项目。

测试故事

当使用 Playwright Test 测试 Web 组件时,测试运行在 Node.js 中,而组件运行在真实的浏览器中。这结合了两者的优势:组件在真实的浏览器环境中运行,触发真实的点击,执行真实的布局,可以进行视觉回归测试。同时,测试可以使用 Node.js 的所有能力以及 Playwright Test 的所有功能。因此,在组件测试期间,可以使用与事后跟踪故事相同的并行、参数化测试。

然而,这引入了一些限制

  • 你不能将复杂的实时对象传递给你的组件。只能传递简单的 JavaScript 对象和内置类型,如字符串、数字、日期等。
test('this will work', async ({ mount }) => {
const component = await mount(<ProcessViewer process={{ name: 'playwright' }}/>);
});

test('this will not work', async ({ mount }) => {
// `process` is a Node object, we can't pass it to the browser and expect it to work.
const component = await mount(<ProcessViewer process={process}/>);
});
  • 你不能在回调中同步地将数据传递给组件
test('this will not work', async ({ mount }) => {
// () => 'red' callback lives in Node. If `ColorPicker` component in the browser calls the parameter function
// `colorGetter` it won't get result synchronously. It'll be able to get it via await, but that is not how
// components are typically built.
const component = await mount(<ColorPicker colorGetter={() => 'red'}/>);
});

解决这些和其他限制的方法快速且优雅:对于被测组件的每种用例,创建一个专门用于测试的该组件的包装器。这不仅可以减轻限制,还可以为测试提供强大的抽象,你可以在其中定义环境、主题和组件渲染的其他方面。

假设你想测试以下组件

input-media.tsx
import React from 'react';

type InputMediaProps = {
// Media is a complex browser object we can't send to Node while testing.
onChange(media: Media): void;
};

export function InputMedia(props: InputMediaProps) {
return <></> as any;
}

为你的组件创建一个故事文件

input-media.story.tsx
import React from 'react';
import InputMedia from './import-media';

type InputMediaForTestProps = {
onMediaChange(mediaName: string): void;
};

export function InputMediaForTest(props: InputMediaForTestProps) {
// Instead of sending a complex `media` object to the test, send the media name.
return <InputMedia onChange={media => props.onMediaChange(media.name)} />;
}
// Export more stories here.

然后通过测试故事来测试组件

input-media.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import { InputMediaForTest } from './input-media.story.tsx';

test('changes the image', async ({ mount }) => {
let mediaSelected: string | null = null;

const component = await mount(
<InputMediaForTest
onMediaChange={mediaName => {
mediaSelected = mediaName;
}}
/>
);
await component
.getByTestId('imageInput')
.setInputFiles('src/assets/logo.png');

await expect(component.getByAltText(/selected image/i)).toBeVisible();
await expect.poll(() => mediaSelected).toBe('logo.png');
});

因此,对于每个组件,你都会有一个故事文件,导出所有实际测试的故事。这些故事运行在浏览器中,并将复杂对象“转换”为可以在测试中访问的简单对象。

底层原理

组件测试的工作原理如下

  • 测试执行后,Playwright 会创建一个测试所需的组件列表。
  • 然后,它会编译一个包含这些组件的 bundle,并使用本地静态 Web 服务器提供服务。
  • 在测试中调用 mount 时,Playwright 会导航到此 bundle 的门面页面 /playwright/index.html,并指示其渲染组件。
  • 事件被封送回 Node.js 环境以进行验证。

Playwright 使用 Vite 来创建组件 bundle 并提供服务。

API 参考

props

在组件挂载时提供 props。

component.spec.tsx
import { test } from '@playwright/experimental-ct-react';

test('props', async ({ mount }) => {
const component = await mount(<Component msg="greetings" />);
});

callbacks / 事件

在组件挂载时提供 callbacks/事件。

component.spec.tsx
import { test } from '@playwright/experimental-ct-react';

test('callback', async ({ mount }) => {
const component = await mount(<Component onClick={() => {}} />);
});

children / 插槽

在组件挂载时提供 children/插槽。

component.spec.tsx
import { test } from '@playwright/experimental-ct-react';

test('children', async ({ mount }) => {
const component = await mount(<Component>Child</Component>);
});

钩子

你可以使用 beforeMountafterMount 钩子来配置你的应用。这允许你设置应用路由器、模拟服务器等,为你提供了所需的灵活性。你还可以从测试中的 mount 调用传递自定义配置,该配置可通过 hooksConfig 夹具访问。这包括需要在组件挂载之前或之后运行的任何配置。下面提供了一个配置路由器的示例

playwright/index.tsx
import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks';
import { BrowserRouter } from 'react-router-dom';

export type HooksConfig = {
enableRouting?: boolean;
}

beforeMount<HooksConfig>(async ({ App, hooksConfig }) => {
if (hooksConfig?.enableRouting)
return <BrowserRouter><App /></BrowserRouter>;
});
src/pages/ProductsPage.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import type { HooksConfig } from '../playwright';
import { ProductsPage } from './pages/ProductsPage';

test('configure routing through hooks config', async ({ page, mount }) => {
const component = await mount<HooksConfig>(<ProductsPage />, {
hooksConfig: { enableRouting: true },
});
await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42');
});

unmount

从 DOM 中卸载已挂载的组件。这对于测试组件在卸载时的行为很有用。用例包括测试“确定要离开吗?”模态框或确保事件处理程序正确清理以防止内存泄漏。

component.spec.tsx
import { test } from '@playwright/experimental-ct-react';

test('unmount', async ({ mount }) => {
const component = await mount(<Component/>);
await component.unmount();
});

update

更新已挂载组件的 props、插槽/children 和/或事件/callbacks。这些组件输入可以随时更改,通常由父组件提供,但有时需要确保你的组件对新的输入做出适当的行为。

component.spec.tsx
import { test } from '@playwright/experimental-ct-react';

test('update', async ({ mount }) => {
const component = await mount(<Component/>);
await component.update(
<Component msg="greetings" onClick={() => {}}>Child</Component>
);
});

处理网络请求

Playwright 提供了一个实验性router 夹具来拦截和处理网络请求。使用 router 夹具有两种方式

  • 调用 router.route(url, handler),其行为类似于 page.route()。有关更多详细信息,请参阅网络模拟指南
  • 调用 router.use(handlers) 并将 MSW 库 的请求处理程序传递给它。

下面是在测试中重用现有 MSW 处理程序的一个示例。

import { handlers } from '@src/mocks/handlers';

test.beforeEach(async ({ router }) => {
// install common handlers before each test
await router.use(...handlers);
});

test('example test', async ({ mount }) => {
// test as usual, your handlers are active
// ...
});

你也可以为特定测试引入一次性处理程序。

import { http, HttpResponse } from 'msw';

test('example test', async ({ mount, router }) => {
await router.use(http.get('/data', async ({ request }) => {
return HttpResponse.json({ value: 'mocked' });
}));

// test as usual, your handler is active
// ...
});

常见问题

@playwright/test@playwright/experimental-ct-{react,svelte,vue} 有什么区别?

test('…', async ({ mount, page, context }) => {
// …
});

@playwright/experimental-ct-{react,svelte,vue} 包装了 @playwright/test,以提供一个额外的内置组件测试专用夹具,名为 mount

import { test, expect } from '@playwright/experimental-ct-react';
import HelloWorld from './HelloWorld';

test.use({ viewport: { width: 500, height: 500 } });

test('should work', async ({ mount }) => {
const component = await mount(<HelloWorld msg="greetings" />);
await expect(component).toContainText('Greetings');
});

此外,它还添加了一些配置选项,你可以在 playwright-ct.config.{ts,js} 中使用。

最后,在底层,每个测试都会重用 contextpage 夹具,作为组件测试的速度优化。它会在每次测试之间重置它们,因此功能上应该等同于 @playwright/test 的保证,即每个测试都会获得一个新的、独立的 contextpage 夹具。

我的项目已经使用了 Vite。我可以重用配置吗?

目前,Playwright 与 bundler 无关,因此它不会重用你现有的 Vite 配置。你的配置可能有很多我们无法重用的东西。所以目前,你需要将你的路径映射和其他高级设置复制到 Playwright 配置的 ctViteConfig 属性中。

import { defineConfig } from '@playwright/experimental-ct-react';

export default defineConfig({
use: {
ctViteConfig: {
// ...
},
},
});

你可以通过 Vite 配置指定插件用于测试设置。注意,一旦你开始指定插件,你也要负责指定框架插件,在这种情况下是 vue()

import { defineConfig, devices } from '@playwright/experimental-ct-vue';

import { resolve } from 'path';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';

export default defineConfig({
testDir: './tests/component',
use: {
trace: 'on-first-retry',
ctViteConfig: {
plugins: [
vue(),
AutoImport({
imports: [
'vue',
'vue-router',
'@vueuse/head',
'pinia',
{
'@/store': ['useStore'],
},
],
dts: 'src/auto-imports.d.ts',
eslintrc: {
enabled: true,
},
}),
Components({
dirs: ['src/components'],
extensions: ['vue'],
}),
],
resolve: {
alias: {
'@': resolve(__dirname, './src'),
},
},
},
},
});

如何使用 CSS 导入?

如果你的组件导入了 CSS,Vite 会自动处理。你还可以使用 CSS 预处理器,如 Sass、Less 或 Stylus,Vite 也会处理它们,无需额外配置。但是,需要安装相应的 CSS 预处理器。

Vite 有一个硬性要求,所有 CSS 模块必须命名为 *.module.[css extension]。如果你的项目通常有自定义构建配置,并且导入形式为 import styles from 'styles.css',则必须重命名文件以正确指示它们应被视为模块。你也可以编写一个 Vite 插件来为你处理这个问题。

有关更多详细信息,请查阅 Vite 文档

如何测试使用 Pinia 的组件?

Pinia 需要在 playwright/index.{js,ts,jsx,tsx} 中初始化。如果你在 beforeMount 钩子内执行此操作,则可以按测试重写 initialState

playwright/index.ts
import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks';
import { createTestingPinia } from '@pinia/testing';
import type { StoreState } from 'pinia';
import type { useStore } from '../src/store';

export type HooksConfig = {
store?: StoreState<ReturnType<typeof useStore>>;
}

beforeMount<HooksConfig>(async ({ hooksConfig }) => {
createTestingPinia({
initialState: hooksConfig?.store,
/**
* Use http intercepting to mock api calls instead:
* https://playwright.net.cn/docs/mock#mock-api-requests
*/
stubActions: false,
createSpy(args) {
console.log('spy', args)
return () => console.log('spy-returns')
},
});
});
src/pinia.spec.ts
import { test, expect } from '@playwright/experimental-ct-vue';
import type { HooksConfig } from '../playwright';
import Store from './Store.vue';

test('override initialState ', async ({ mount }) => {
const component = await mount<HooksConfig>(Store, {
hooksConfig: {
store: { name: 'override initialState' }
}
});
await expect(component).toContainText('override initialState');
});

如何访问组件的方法或其实例?

在测试代码中访问组件的内部方法或其实例既不推荐也不支持。相反,应侧重于从用户的角度观察和与组件交互,通常通过点击或验证页面上是否可见某些内容。当测试避免与内部实现细节(例如组件实例或其方法)交互时,它们会变得更不易碎且更有价值。请记住,如果从用户角度运行测试时失败,很可能意味着自动化测试发现了代码中的真实错误。