명령어
명령어는 서버에서 특정 함수를 호출하고 그 결과를 브라우저로 다시 전달하는 기능입니다. Vitest는 브라우저 테스트에서 활용할 수 있는 다양한 내장 명령어를 제공합니다.
내장 명령어
파일 처리
readFile
, writeFile
, removeFile
API를 사용하여 브라우저 테스트 환경에서 파일을 처리할 수 있습니다. Vitest 3.2부터 모든 경로는 프로젝트 루트(수동으로 재정의하지 않는 한 process.cwd()
)를 기준으로 해석됩니다. 이전 버전에서는 테스트 파일을 기준으로 경로가 확인되었습니다.
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(CDP)에 접근할 수 있도록 합니다. 이 기능은 주로 라이브러리 개발자가 이를 기반으로 도구를 구축할 때 유용합니다.
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
를 참조하여 구성 및 userEvent
, page
옵션에서 자동 완성을 얻는 것을 잊지 마십시오.
/// <reference types="@vitest/browser/providers/playwright" />
사용자 정의 webdriverio
명령어
Vitest는 컨텍스트 객체에 일부 WebdriverIO 관련 속성을 노출합니다.
browser
는WebdriverIO.Browser
API입니다.
Vitest는 명령어가 호출되기 전에 browser.switchToFrame
을 호출하여 WebdriverIO 컨텍스트를 테스트 iframe으로 자동 전환합니다. 따라서 $
및 $$
메서드는 오케스트레이터가 아닌 iframe 내부의 요소를 참조하지만, 비-WebdriverIO API는 여전히 부모 프레임의 컨텍스트를 참조합니다.