コマンド
コマンドは、サーバー上で定義された関数をブラウザから呼び出し、その結果を受け取るための機能です。Vitest は、ブラウザテストで使用できるいくつかの組み込みコマンドを提供しています。
組み込みコマンド
ファイル操作
ブラウザテスト内でファイルを操作するために、readFile、writeFile、removeFile API を使用できます。これらの 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 を使用している場合は、tsconfig の "compilerOptions.types" フィールドに @vitest/browser/providers/playwright を追加して、設定および userEvent と page オプションでオートコンプリートを取得することを忘れないでください。
{
"compilerOptions": {
"types": ["@vitest/browser/providers/playwright"]
}
}カスタム webdriverio コマンド
Vitest は、コンテキストオブジェクトにいくつかの webdriverio 固有のプロパティを提供しています。
browserはWebdriverIO.BrowserAPI です。
Vitest は、コマンドが呼び出される前に browser.switchToFrame を呼び出すことで、webdriver コンテキストをテスト iframe に自動的に切り替えます。そのため、$ および $$ メソッドはオーケストレーターではなく iframe 内の要素を参照しますが、非 webdriver API は親フレームのコンテキストを参照し続けます。
TIP
TypeScript を使用している場合は、tsconfig の "compilerOptions.types" フィールドに @vitest/browser/providers/webdriverio を追加して、オートコンプリートを取得することを忘れないでください。
{
"compilerOptions": {
"types": ["@vitest/browser/providers/webdriverio"]
}
}