跳至主要内容

组件(实验性功能)

简介

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 Test组件

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>

This file defines an html file that will be used to render components during testing. It must contain element with id="root", that's where components are mounted. It must also link the script called 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会生成测试所需的组件列表。
  • 然后它会编译一个包含这些组件的包,并使用本地静态网络服务器提供服务。
  • Upon the mount call within the test, Playwright navigates to the facade page /playwright/index.html of this bundle and tells it to render the component.
  • 事件被编组回Node.js环境以进行验证。

Playwright 正在使用 Vite 来创建组件包并提供服务。

API参考

属性

在组件挂载时提供props。

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

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

回调/事件

在组件挂载时提供回调/事件。

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

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

子元素 / 插槽

在组件挂载时提供子元素/插槽。

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');
});

卸载

将已挂载的组件从DOM中卸载。这对于测试组件在卸载时的行为非常有用。使用场景包括测试"您确定要离开吗?"模态框,或确保正确清理事件处理程序以防止内存泄漏。

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

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

更新

更新已挂载组件的props、slots/子组件和/或events/回调函数。这些组件输入可以随时变化,通常由父组件提供,但有时需要确保您的组件对新输入做出适当响应。

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 夹具:

以下是在测试中重用现有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 是与打包工具无关的,因此它不会复用您现有的 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会自动处理它。您还可以使用Sass、Less或Stylus等CSS预处理器,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.dev/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');
});

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

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