はじめに
お疲れ様です、りつです。
Viteで「React × TypeScript」のプロジェクトを作成し、テスト実装中に遭遇したエラーです。
問題
コンポーネントテストを行うためにApp.spec.tsx
を作成し、テストを実装したのですがtoBeInTheDocument()
を使用すると、VSCode上で以下のエラーが表示されました。
エラー内容
エラー内容
プロパティ 'toBeInTheDocument' は型 'JestMatchers<HTMLElement>' に存在しません。
エラー画像
ソースコード
src/__tests__/App.spec.tsx
import { ChakraProvider, defaultSystem } from "@chakra-ui/react";
import App from "../App";
import { render, screen } from "@testing-library/react";
describe("App", () => {
it("タイトルがあること", () => {
render(<ChakraProvider value={defaultSystem}><App /></ChakraProvider>);
const title = screen.getByTestId("title");
expect(title).toBeInTheDocument();
});
});
解決方法
tsconfig.app.json
のinclude
設定に./jest.setup.ts
を追記することで解消されました。
修正したソースコード
tsconfig.app.json
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"paths": {
"@/*": ["./src/*"]
}
},
+ "include": ["src","./jest.setup.ts"]
}
【参考】その他の設定ファイルの中身
tsconfig.json
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"jsx": "react-jsx",
"types": ["node", "jest", "@testing-library/jest-dom"],
"paths": {
"@/*": ["./src/*"]
}
}
}
jest.setup.ts
import "@testing-library/jest-dom";
require("dotenv").config();
if(!global.structuredClone){
global.structuredClone = function structuredClone(objectToClone: any) {
if (objectToClone === undefined) return undefined;
return JSON.parse(JSON.stringify(objectToClone));
};
}
おわりに
同様のエラーに対する解決方法はいくつかあるようですので、お困りの際は以下の記事も参考にしてみてください。
- 方法1:
tsconfig.json
のinclude
を修正
- 方法2:
tsconfig.json
のCompilerOptions.types
を修正
自分の環境だといずれの方法でも解消されず(例えば、tsconfig.json
のinclude
を修正した場合は以下のエラーに発展してしまったので)、tsconfig.app.json
に追記する形で対応しました。
エラー内容
エラー内容
参照されているプロジェクト '/home/ritsu/workspace/type-class/tsconfig.app.json' には、設定 "composite": true が必要です。
参照されたプロジェクト '/home/ritsu/workspace/type-class/tsconfig.app.json' は、生成を無効にできません。
参照されているプロジェクト '/home/ritsu/workspace/type-class/tsconfig.node.json' には、設定 "composite": true が必要です。
参照されたプロジェクト '/home/ritsu/workspace/type-class/tsconfig.node.json' は、生成を無効にできません。
エラー画像
参考