Open4
VitestでReactのコンポーネントをテストする
まずはVitestを入れる
npm install -D vitest@3.0.5
package.jsonに以下を追記
package.json
{
"scripts": {
"test": "vitest"
}
}
するとnpm run test
でテストを実行できる
vite.config.tsの内容を勝手に読み込んでくれる
If present,
vitest
will read your rootvite.config.ts
to match with the plugins and setup as your Vite app. For example, your Vite resolve.alias and plugins configuration will work out-of-the-box.
次にReact Testing Libraryを入れる
npm install -D @testing-library/react@16.2.0 @testing-library/dom@10.4.0
この時点ではまだコンポーネントのテストはできない。下のファイルを作成してテストを実行するとReferenceError: document is not defined
と表示される
sample.test.tsx
import { render } from '@testing-library/react';
import { test } from 'vitest';
function Sample() {
return <button>button</button>;
}
test('sample', () => {
render(<Sample />);
});
happy-domを入れる
npm install -D happy-dom@17.1.0
vite.config.tsに追記
vite.config.ts
/// <reference types="vitest" />
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
test: {
environment: 'happy-dom',
},
});
すると前述のテストコードが動くようになる
jest-domを入れる
npm install -D @testing-library/jest-dom@6.6.3
新たにファイルを作成する
vitest-setup.ts
import '@testing-library/jest-dom/vitest';
vite.config.tsに以下を追記
test: {
setupFiles: ['./vitest-setup.ts']
}
するとjest-domのマッチャーが使えるようになる
import { render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
function Sample() {
return <button>button</button>;
}
test('sample', () => {
render(<Sample />);
expect(screen.getByText('button')).toBeInTheDocument();
});
上記のコードではtoBeInTheDocument
マッチャーの部分で
Property 'toBeInTheDocument' does not exist on type 'Assertion<HTMLElement>'.
とTypeScriptのエラーが出る。これを解消するには以下を追記する
tsconfig.app.json
{
"include": ["src", "vitest-setup.ts"]
}
ログインするとコメントできます