Jestでテストを実行するときに以下のようなエラーに遭遇しました。その解消法を示します。
Jest encountered an unexpected token Jest failed to parse a file.・・・
上記エラーが出た場合はjest.config.js、tsconfig.jest.jsonをルートディレクトリに作成し以下のように記載することでエラーを解消することができました。
jest.config.js
/** @type {import('jest').Config} */
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.(ts|tsx)$": [
"ts-jest",
{
tsconfig: "./tsconfig.jest.json",
babelConfig: true,
},
],
},
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/$1",
},
};
tsconfig.jest.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"jsx": "react-jsx",
}
}
TypeError: expect(...).toHaveTextContent is not a functio
上記エラーが出た場合は
以下のように「import "@testing-library/jest-dom";」を記入することで解消しました。
import "@testing-library/jest-dom";
・
・
expect(spans[0]).toHaveTextContent("テスト");
・
・