跳到主要內容

元件 (實驗性)

簡介

Playwright 測試現在可以測試您的元件了。

範例

以下是一個典型的元件測試範例

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 測試新增至現有專案非常容易。以下是在 React、Vue 或 Svelte 專案中啟用 Playwright 測試的步驟。

步驟 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 測試用於測試網頁元件時,測試會在 Node.js 中執行,而元件會在真實瀏覽器中執行。這結合了兩者的優點:元件在真實的瀏覽器環境中執行、觸發真實的點擊、執行真實的版面配置、視覺迴歸是可行的。同時,測試可以使用 Node.js 的所有功能以及 Playwright 測試的所有功能。因此,在元件測試期間,可以使用相同的平行、參數化測試和相同的事後追蹤故事。

然而,這引入了一些限制

  • 您無法將複雜的即時物件傳遞給您的元件。只能傳遞純 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 會建立測試所需的元件清單。
  • 然後,它會編譯一個包含這些元件的套件,並使用本機靜態網路伺服器提供該套件。
  • 在測試中的 mount 呼叫時,Playwright 會導航到此套件的外觀頁面 /playwright/index.html,並告知它渲染元件。
  • 事件會被編組回 Node.js 環境以進行驗證。

Playwright 正在使用 Vite 來建立元件套件並提供它。

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

在掛載時將 callbacks/events 提供給元件。

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

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

children / slots

在掛載時將 children/slots 提供給元件。

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

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

hooks

您可以使用 beforeMountafterMount hooks 來設定您的應用程式。這讓您可以設定諸如應用程式路由器、假伺服器等,為您提供所需的彈性。您也可以從測試中的 mount 呼叫傳遞自訂設定,可以從 hooksConfig fixture 存取。這包括任何需要在掛載元件之前或之後執行的設定。以下提供設定路由器的範例

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、slots/children 和/或 events/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 fixture 來攔截和處理網路請求。有兩種方法可以使用 router fixture

以下是在測試中重複使用現有 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 以提供額外的內建元件測試特定 fixture,稱為 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 fixture,作為元件測試的速度最佳化。它會在每個測試之間重設它們,因此在功能上應等同於 @playwright/test 的保證,即您獲得每個測試新的、隔離的 contextpage fixture。

我的專案已經使用 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'),
},
},
},
},
});

我該如何測試使用 Pinia 的元件?

Pinia 需要在 playwright/index.{js,ts,jsx,tsx} 中初始化。如果您在 beforeMount hook 內執行此操作,則可以在每個測試的基礎上覆寫 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.org.tw/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');
});

我該如何存取元件的方法或其實例?

不建議也不支援在測試程式碼中存取元件的內部方法或其實例。相反地,重點應該放在從使用者的角度觀察元件並與之互動,通常是透過點擊或驗證頁面上是否可見某些內容。當測試避免與內部實作細節(例如元件實例或其方法)互動時,測試會變得更不容易出錯且更有價值。請記住,如果從使用者的角度執行測試失敗,則可能表示自動化測試已發現程式碼中的真正錯誤。