公式では babel でバベってやるやり方がメインで紹介されていますが
(https://jestjs.io/docs/ja/getting-started#typescript-%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B)
ちょっと違うやり方でやります。
TypeScript support in Babel is just transpilation, Jest will not type-check your tests as they are ran. If you want that, you can use ts-jest.
と言われてるように、バベると型検査されないので
型検査が必要な場合には ts-jest を使うのがいいですね。
セットアップ
パッケージを入れます:
npm install --save-dev typescript jest ts-jest @types/jest
Jest の設定は package.json にも書いてみます:
{
"jest": {
"moduleFileExtensions": [
"ts",
"js"
],
"transform": {
"^.+\\.ts$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.json"
}
},
"testMatch": [
"**/tests/**/*.test.ts"
]
}
}
testMatch がテスト対象ですね。
${projectRoot}/tests/ 以下の
*.test.ts に書かれたテストスペックが実行対象になります。
transform は ts-jest で TypeScript をよしなに実行してもらうのに必要です。
SyntaxError: Unexpected identifier とか出た場合は変換できてないので指定が漏れてないかチェックします。
あとは globals > ts-jest > tsConfig に tsconfig.json を読むように指定します。これで tsconfig の構成でテストできるようになります。
👉 https://jestjs.io/docs/ja/configuration
Jest の config は
ほかに jest.config.js として export する書き方や、
JSONとして jest.config.json のようにして実行時にオプションで指定もできます。
その場合は jest 以下を記述するようにします。
import のエイリアスを指定
import するときに相対パスだとちょっと長ったらしいので
import some from "#/some/module"; とかで
ソースディレクトリからモジュールを読み込めるようにしておくと若干嬉しいです:
{
"compilerOptions": {
"baseUrl": "./src/",
"paths": {
"#/*": ["*"]
},
}
}
Jest の設定にも追記します:
{
"jest": {
"moduleNameMapper": {
"^#/(.+)": "<rootDir>/src/$1"
}
}
}
これで #/some/module は ${projectRoot}/src/some/module にマップされます。
テストを書く
テストの書き方自体はいつもの感じで書けます。
無駄に型指定しかするとこんな感じです:
import greet from "#/greet";
describe('greet', (): void => {
test('should say hello to Tom.', (): void => {
const response: string = greet('Tom');
expect(response).toBe('Hello, Tom!');
});
})
export default (name: string): string => `Hello, ${name}!`;
テストを書けました。
テストの実行に追加で指定は必要ありません (他にオプションが必要なければ)。
npm test で実行できるようにしましょう。:
{
"scripts": {
"test": "jest"
}
}
> npm test
PASS tests/greet.test.ts
greet
✓ should say hello to Tom. (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.829s, estimated 3s
Ran all test suites.
これで OK です。
あとは https://jestjs.io/docs/ja/getting-started にあるドキュメント に沿って、効率的にテストを書いていくとよいですね!