命令
命令是一個函式,它會在伺服器端被呼叫,並將結果傳回瀏覽器端。Vitest 提供了數個內建命令,您可以在瀏覽器測試中使用。
內建命令
檔案操作
您可以使用 readFile
、writeFile
和 removeFile
API 在瀏覽器測試中處理檔案。所有路徑都會相對於測試檔案解析,即使它們是在位於另一個檔案中的輔助函式中呼叫的。
預設情況下,Vitest 使用 utf-8
編碼,但您可以使用選項進行覆寫。
TIP
出於安全原因,此 API 遵循 server.fs
的限制。
import { server } from '@vitest/browser/context';
const { readFile, writeFile, removeFile } = server.commands;
it('handles files', async () => {
const file = './test.txt';
await writeFile(file, 'hello world');
const content = await readFile(file);
expect(content).toBe('hello world');
await removeFile(file);
});
CDP 會話
Vitest 透過從 @vitest/browser/context
匯出的 cdp
方法,提供了存取原始 Chrome Devtools Protocol 的方法。這對於函式庫作者在其上建構工具非常有用。
import { cdp } from '@vitest/browser/context';
const input = document.createElement('input');
document.body.appendChild(input);
input.focus();
await cdp().send('Input.dispatchKeyEvent', {
type: 'keyDown',
text: 'a',
});
expect(input).toHaveValue('a');
WARNING
CDP 會話僅適用於 playwright
提供者,且僅在使用 chromium
瀏覽器時。您可以在 playwright 的 CDPSession
文件中閱讀更多相關資訊。
自訂命令
您也可以透過 browser.commands
設定選項新增自己的命令。如果您正在開發函式庫,可以透過插件中的 config
鉤子提供它們:
import type { Plugin } from 'vitest/config';
import type { BrowserCommand } from 'vitest/node';
const myCustomCommand: BrowserCommand<[arg1: string, arg2: string]> = (
{ testPath, provider },
arg1,
arg2
) => {
if (provider.name === 'playwright') {
console.log(testPath, arg1, arg2);
return { someValue: true };
}
throw new Error(`provider ${provider.name} is not supported`);
};
export default function BrowserCommands(): Plugin {
return {
name: 'vitest:custom-commands',
config() {
return {
test: {
browser: {
commands: {
myCustomCommand,
},
},
},
};
},
};
}
然後您可以透過從 @vitest/browser/context
匯入它,在測試中呼叫它:
import { commands } from '@vitest/browser/context';
import { expect, test } from 'vitest';
test('custom command works correctly', async () => {
const result = await commands.myCustomCommand('test1', 'test2');
expect(result).toEqual({ someValue: true });
});
// if you are using TypeScript, you can augment the module
declare module '@vitest/browser/context' {
interface BrowserCommands {
myCustomCommand: (
arg1: string,
arg2: string
) => Promise<{
someValue: true;
}>;
}
}
WARNING
如果自訂函式與內建函式同名,則會覆寫內建函式。
自訂 playwright
命令
Vitest 在命令上下文中公開了幾個 playwright
特定的屬性。
page
參考包含測試 iframe 的完整頁面。這是協調器 HTML,您很可能不應觸碰它以免造成問題。frame
是一個異步方法,它將解析測試器Frame
。它具有與page
類似的 API,但不支援某些方法。如果您需要選取元素,應該優先使用context.iframe
,因為它更穩定且更快。iframe
是一個FrameLocator
,應用於查詢頁面上的其他元素。context
指向唯一的 BrowserContext。
import { BrowserCommand } from 'vitest/node';
export const myCommand: BrowserCommand<[string, number]> = async (
ctx,
arg1: string,
arg2: number
) => {
if (ctx.provider.name === 'playwright') {
const element = await ctx.iframe.findByRole('alert');
const screenshot = await element.screenshot();
// do something with the screenshot
return difference;
}
};
TIP
如果您正在使用 TypeScript,請不要忘記將 @vitest/browser/providers/playwright
新增到您的 tsconfig
"compilerOptions.types" 欄位中,以便在設定和 userEvent
和 page
選項中獲得自動完成:
{
"compilerOptions": {
"types": ["@vitest/browser/providers/playwright"]
}
}
自訂 webdriverio
命令
Vitest 在上下文物件上公開了一些 webdriverio
特定的屬性。
browser
是WebdriverIO.Browser
API。
Vitest 會在呼叫命令之前自動將 webdriver
上下文切換到測試 iframe,方法是呼叫 browser.switchToFrame
,因此 $
和 $$
方法參考的是 iframe 內的元素,而不是協調器中的元素,但非 webdriver API 仍會參考父框架上下文。
TIP
如果您正在使用 TypeScript,請不要忘記將 @vitest/browser/providers/webdriverio
新增到您的 tsconfig
"compilerOptions.types" 欄位中,以便獲得自動完成:
{
"compilerOptions": {
"types": ["@vitest/browser/providers/webdriverio"]
}
}