元件 (實驗性)
簡介
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 或 Solid 專案啟用 Playwright Test 的步驟。
第一步: 為您的相應框架安裝 Playwright Test 來測試元件
- npm
- yarn
- pnpm
npm init playwright@latest -- --ct
yarn create playwright --ct
pnpm create playwright --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}
- React
- Solid
- Svelte
- Vue
import { test, expect } from '@playwright/experimental-ct-react';
import App from './App';
test.use({ viewport: { width: 500, height: 500 } });
test('should work', async ({ mount }) => {
const component = await mount(<App />);
await expect(component).toContainText('Learn React');
});
import { test, expect } from '@playwright/experimental-ct-vue';
import App from './App.vue';
test.use({ viewport: { width: 500, height: 500 } });
test('should work', async ({ mount }) => {
const component = await mount(App);
await expect(component).toContainText('Vite + Vue');
});
如果使用 TypeScript 和 Vue,請確保將 vue.d.ts
檔案添加到您的專案中:
declare module '*.vue';
import { test, expect } from '@playwright/experimental-ct-svelte';
import App from './App.svelte';
test.use({ viewport: { width: 500, height: 500 } });
test('should work', async ({ mount }) => {
const component = await mount(App);
await expect(component).toContainText('Vite + Svelte');
});
import { test, expect } from '@playwright/experimental-ct-solid';
import App from './App';
test.use({ viewport: { width: 500, height: 500 } });
test('should work', async ({ mount }) => {
const component = await mount(<App />);
await expect(component).toContainText('Learn Solid');
});