명령어
명령어는 서버에서 특정 함수를 호출하고 그 결과를 브라우저로 전달하는 역할을 합니다. 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 });
});
// TypeScript를 사용하는 경우 모듈을 확장하여 타입을 정의할 수 있습니다.
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();
// 스크린샷으로 무언가를 수행합니다.
return difference;
}
};
TIP
TypeScript를 사용하는 경우 구성 및 userEvent
, page
옵션에서 자동 완성을 얻으려면 tsconfig
의 "compilerOptions.types" 필드에 @vitest/browser/providers/playwright
를 추가해야 합니다.
{
"compilerOptions": {
"types": ["@vitest/browser/providers/playwright"]
}
}
사용자 정의 webdriverio
명령어
Vitest는 컨텍스트 객체에 일부 webdriverio
관련 속성을 제공합니다.
browser
:WebdriverIO.Browser
API입니다.
Vitest는 명령이 호출되기 전에 browser.switchToFrame
을 호출하여 webdriver
컨텍스트를 테스트 iframe으로 자동으로 전환합니다. 따라서 $
및 $$
메서드는 오케스트레이터가 아닌 iframe 내부의 요소를 가리키지만, 비-webdriver API는 여전히 부모 프레임 컨텍스트를 참조합니다.
TIP
TypeScript를 사용하는 경우 자동 완성을 얻으려면 tsconfig
의 "compilerOptions.types" 필드에 @vitest/browser/providers/webdriverio
를 추가해야 합니다.
{
"compilerOptions": {
"types": ["@vitest/browser/providers/webdriverio"]
}
}