jest + React Testing Library の設定
https://jestjs.io/blog/2022/04/25/jest-28
jest v28からいろいろ設定が変わった
testEnvironmentの初期値がjsdom -> node
jest-environment-jsdom が外れたから使う場合は別途installしてね
react-testing-libraryを使う際の設定方法を書いていく
ts-jestを使う
yarn add -D jest @types/jest ts-jest
yarn ts-jest config:init
jest.config.jsが作られる
react-testing-library
yarn add -D @testing-library/react @testing-library/jest-dom @testing-library/user-event @testing-library/react-hooks
テストコードを書いて実行するとエラー
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
jest.config.jsのtestEnvironment: 'node'をnodeからjsdomに変える必要があるがただ書き換えてもエラー
Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.
なのでjest-environment-jsdomをインストールする
jest.config.jsをtestEnvironment: 'jsdom'もしくはjest-environment-jsdomに書き換えれば動くようになる
各テストファイルでimport from "@testing-library/jest-dom を省略する
code:jest.setup.ts
import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
afterEach(() => cleanup());
code:tsconfig.json
{
compileOptions: {
//
},
+ "include": "src", "vitest.setup.ts",
}
code:jest.config.json
{
//省略
+ "setupFilesAfterEnv": "<rootDir>/jest.setup.ts",
}
vitestの場合
code:vite.congig.ts
export default defineConfig({
plugins: react(),
test: {
+ setupFiles: "./vitest.setup.ts",
},
});
参考:
https://zenn.dev/keita_hino/articles/488d31e8c4a240
https://jestjs.io/blog/2022/04/25/jest-28