LoginSignup
7

More than 5 years have passed since last update.

React + TypeScrypt + Jest(ts, tsx) 環境をcreate-react-appから最速で構築する

Last updated at Posted at 2018-06-20

そして全ては幻想だった...(6/23追記)

npx create-react-app my-app --scripts-version=react-scripts-ts
cd my-app
yarn test

でいけてた。完全に自分の設定ミスだった :angel_tone2:

setup
npx create-react-app my-app --scripts-version=react-scripts-ts
cd my-app
mkdir src/__test__/ src/__test__/__mocks__/
touch src/__test__/__mocks__/fileMock.js
yarn add -D ts-jest @types/jest identity-obj-proxy
package.json
  "scripts": {
    "test": "jest"
  },

  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__test__/__mocks__/fileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    }
  },
src/__test__/__mocks__/fileMock.js
module.exports = {};
fin.
yarn test
# yarn run v1.7.0
# $ jest
# PASS  src/App.test.tsx
#  ✓ renders without crashing (20ms)

解説

「--scripts-version=react-scripts-ts」でTypeScryptの実行環境までは提供してくれるが、
TSとJestとの互換性までは用意してくれないし、「react-scripts-ts test」では拡張性に限界があるので、test実行環境は一から作る必要がある。

$ react-scripts-ts test --env=jsdom
Out of the box, Create React App only supports overriding these Jest options:
• collectCoverageFrom
• coverageReporters
• coverageThreshold
• snapshotSerializers
• moduleNameMapper.
These options in your package.json Jest configuration are not currently supported by Create React App:
• transform
• testRegex
• moduleFileExtensions
If you wish to override other Jest options, you need to eject from the default setup. You can do so by running npm run eject but remember that this is a one-way operation. You may also file an issue with
Create React App to discuss supporting more options out of the box.

transform

Jestはdefaultではimportなどの構文をサポートしていないため、ES6以降の構文で書いている場合は変換してやる必要がある。TSの場合 ts-jest というローダー(トランスパイラー?)を使う。js, jsxは babel-jest を使うっぽい。

testRegex

Jestがテストファイルとして検出するために使用する正規表現。
defaultでは.ts, .tsxは含まれていないので必須。

moduleFileExtensions

モジュールが使用するファイル拡張子の指定。
TSの場合はここで指定されているように「ts, tsx」を追加する必要がある。

moduleNameMapper

js以外のファイルをimportしている場合、コンパイルエラーが発生してしまうので、拡張子毎に指定したmockへとマップさせエラーを回避する。
Mocking CSS Modules
"Syntax Error: Invalid or unexpected token" with .png

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
7