LoginSignup
195
139

More than 3 years have passed since last update.

TypeScript のテストを Jest (ts-jest) でやってみる

Last updated at Posted at 2019-04-05

公式では 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 を使うのがいいですね。

セットアップ

パッケージを入れます:

console
npm install --save-dev typescript jest ts-jest @types/jest

Jest の設定は package.json にも書いてみます:

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 に書かれたテストスペックが実行対象になります。

transformts-jest で TypeScript をよしなに実行してもらうのに必要です。
SyntaxError: Unexpected identifier とか出た場合は変換できてないので指定が漏れてないかチェックします。

あとは globals > ts-jest > tsConfigtsconfig.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"; とかで
ソースディレクトリからモジュールを読み込めるようにしておくと若干嬉しいです:

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src/",
    "paths": {
      "#/*": ["*"]
    },   
  }
}

Jest の設定にも追記します:

package.json
{
  "jest": {
    "moduleNameMapper": {
      "^#/(.+)": "<rootDir>/src/$1"
    }
  }
}

これで #/some/module${projectRoot}/src/some/module にマップされます。

テストを書く

テストの書き方自体はいつもの感じで書けます。
無駄に型指定しかするとこんな感じです:

tests/greet.test.ts
import greet from "#/greet";

describe('greet', (): void => {
    test('should say hello to Tom.', (): void => {
        const response: string = greet('Tom');
        expect(response).toBe('Hello, Tom!');
    });
})
src/greet.ts
export default (name: string): string => `Hello, ${name}!`;

テストを書けました。
テストの実行に追加で指定は必要ありません (他にオプションが必要なければ)。
npm test で実行できるようにしましょう。:

package.json
{
  "scripts": {
    "test": "jest"
  }
}

console
> 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 にあるドキュメント に沿って、効率的にテストを書いていくとよいですね!

195
139
2

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
195
139