1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jest failed to parse a file. エラーが生じる

Posted at

初めに

昨年3月まで医療職で、そこからWeb制作を学習。
Web制作以外にもReactスキルを身につけたいと思い、今年の1月よりJISOUに参加しました!

今回はReact×TypescriptプロジェクトをJEST・React Testing Libraryでテストした際のエラーを共有します。

問題点

ターミナルにてnpm run testを叩くと以下のエラーが返ってくる。

Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

どうやらテストの環境設定がうまくできていないようです。

解決策

以下をターミナルに入力

$ npm i --save-dev jest
$ npm i --save-dev @types/jest
$ npm i --save-dev ts-jest

jest.config.jsを作る

export default {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["./jest.setup.ts"],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
  },
};

jest.setup.tsを作る(拡張子がjsではない)

import "@testing-library/jest-dom";

require("dotenv").config();

以下をターミナルに入力

$ npm install dotenv

tsconfig.jsonを変更する。

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["node", "jest", "@testing-library/jest-dom"]
  },
  "include": ["src"],
}

以下をターミナルに入力

$ npm i --save-dev @testing-library/react
$ npm i --save-dev @testing-library/jest-dom 
$ npm i --save-dev jest-environment-jsdom 
$ npm i --save-dev @testing-library/user-event

package.jsonにtestを追加する

    "test": "jest"

終わりに

毎回CI/CDのあたりでつまづきます。
ただつまづかないスキルではなく、つまづいた時にそれを乗り越えるスキルを身につけたいです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?