Zenn
Open4

VitestでReactのコンポーネントをテストする

ykttdnykttdn

まずはVitestを入れる
https://vitest.dev/guide/

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 root vite.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.

ykttdnykttdn

次にReact Testing Libraryを入れる
https://github.com/testing-library/react-testing-library#installation

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 />);
});
ykttdnykttdn

happy-domを入れる
https://github.com/capricorn86/happy-dom/wiki/Getting-started#installation

npm install -D happy-dom@17.1.0

vite.config.tsに追記
https://vitest.dev/config/#environment

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',
  },
});

すると前述のテストコードが動くようになる

ykttdnykttdn

jest-domを入れる
https://github.com/testing-library/jest-dom?tab=readme-ov-file#installation

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"]
}
ログインするとコメントできます