そして全ては幻想だった...(6/23追記)
npx create-react-app my-app --scripts-version=react-scripts-ts cd my-app yarn test
でいけてた。完全に自分の設定ミスだった
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
"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"
}
},
module.exports = {};
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