dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

TypeScriptでJestを使うときの設定(ts-jest, @types/jestなど)

メモ。
TypeScript を使ったプロジェクトに Jest を導入する時に必要なパッケージや設定、とくに ts-jest@types/jest が必ず必要なのかどうかがよくわかってなかったので調べた。


先にまとめ

TypeScript -> JavaScriptコンパイルを TypeScript 自身でやるか Babel に任せるかで必要な設定が異なる。
Babel 7 から TypeScript がサポートされた

  • @types/jest は(テストファイルも型チェックするなら)両方で必要
  • TypeScript のコンパイルに Babel を使う場合、@preset/typescriptbabel-jest をインストールしておけば ts-jest は不要
  • TypeScript のコンパイルに TypeScript を使う場合、 ts-jest が必要。jest.config.jsonpreset: 'ts-jest' を指定する


1. TypeScript を使った場合の設定

ts-jest 公式ドキュメントに従い、ts-jest@types/jest をインストールする。

https://kulshekhar.github.io/ts-jest/user/install

$ npm install -D jest typescript ts-jest @types/jest

jest.config.jspresetts-jest を指定する。(Configuration > Basic usage より)

// jest.config.js
module.exports = {
  // [...]
  // Replace `ts-jest` with the preset you want to use
  // from the above list
  preset: 'ts-jest'
};


2. Babel を使った場合の設定

jest, typescript, @types/jest が必要なのは 1 と同じ。

$ npm install -D jest typescript @types/jest

それ以外は Jest 公式ドキュメントの Getting Started に記載の通り。
Getting Started · Jest

Babel との併用のために babel-jest @babel/core @babel/preset-env 、さらに TypeScript のために @babel/preset-typescript が必要になる。

$ npm install -D babel-jest @babel/core @babel/preset-env @babel/preset-typescript

そして Babel の設定にインストールした preset を書いておく。

// babel.config.js
module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-typescript',
  ],
};

ドキュメントでは @babel/preset-env{targets: {node: 'current'} を指定しているが、なくても動く。プロジェクトに合わせて設定すればいいはず。

Jest 側の設定(jest.config.json)は特に不要。


注意事項

2 の Babel を使った場合、以下に記載されているように制限事項がいくつかある。

特に Babel でのコンパイルの場合 型チェックをしない というのが大きな差。

たとえばこんなスクリプトを書いててもテストでは無視される。

// main.ts
export function add100(a: number) {
  const b: number = '100'; // 型エラー
  return a + b;
}
// main.spec.ts
import { add100 } from './main';

describe('add100', () => {
  it('should be 1 + 100 = 101', () => {
    expect(add100(1)).toEqual(101);
  });
});
# テスト実行結果。コンパイルエラーでなくアサーションでエラー
$ npm test
 FAIL  src/main.spec.ts
  ● add100 › should be 1 + 100 = 101

    expect(received).toEqual(expected)

    Expected: 101
    Received: "1100"

また、型チェックをしないので @types/jest はインストールしなくてもテストは実行できる。


検証コード

https://github.com/zaki-yama/typescript-jest-setting-sample