golangの日記

Go言語を中心にプログラミングについてのブログ

TypeScript jestを使ったユニットテスト

typescript.png


jestを使ったTypeScriptの単体テスト


GitHub
* https://github.com/facebook/jest

ドキュメント
* https://jestjs.io/ja/


必要なnpmパッケージのインストール

$ yarn add --dev typescript jest ts-jest ts-node @types/jest @types/node

or

$ npm i --save-dev typescript jest ts-jest ts-node @types/jest @types/node





目次



TypeScriptの設定ファイル

$ npx tsc --init


jestの設定ファイル


設定ファイルのドキュメント: https://jestjs.io/ja/docs/configuration


$ npx jest --init

? Would you like to use Jest when running "test" script in "package.json"? › (Y/n)

# jest の設定ファイルを .ts か .js にするかの選択。TypeScript にすると ts-node パッケージが必須になる。
# デフォルトで .js だし、特に TypeScript で記述する必要性はないと思う
? Would you like to use Typescript for the configuration file? › (y/N)

? Choose the test environment that will be used for testing › - Use arrow-keys. Return to submit.
❯   node
    jsdom (browser-like)

? Do you want Jest to add coverage reports? › (y/N)

? Which provider should be used to instrument code for coverage? › - Use arrow-keys. Return to submit.
❯   v8
    babel

? Automatically clear mock calls and instances between every test? › (y/N)


jest.config.js に以下の 3 つを追記

// ./src 以下のテストファイルを再帰的に探す
roots:
    [
        "<rootDir>/src",
    ],

// __tests__ディレクトリ以下にあるファイルか *.spec.ts, *.test.ts ファイルを探す
testMatch:
    [
        "**/__tests__/**/*.+(ts|tsx|js)",
        "**/?(*.)+(spec|test).+(ts|tsx|js)",
    ],

// .ts を .js にする
transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
},



ディレクトリ構成

 ./
 ├── jest.config.js
 ├── node_modules
 ├── package.json
 ├── src
 │   └── ts
 │       ├── index.ts
 │       └── calc
 │           ├── calc.ts
 │           └── calc.test.ts
 ├── tsconfig.json
 └── yarn.lock

テストしたいファイルの隣に calc.test.ts を作成できるし
index.test.ts を追加してテストファイルを分けることもできて良い


./src/ts/calc/calc.ts

export function sum(...a: number[]): number {
    let total = 0
    for (const n of a) total += n;
    return total;
}


./src/ts/calc/calc.test.ts

import {sum} from './calc';

test('sum', () => {
    expect(sum(10, 10, 10)).toBe(30);
});

テストのAPIに関するドキュメント: https://jestjs.io/ja/docs/api (これ見ると全部わかる)


テストの実行

$ yarn test
or
$ npm test
or
$ npx jest


PASS src/ts/calc/calc.test.ts
  ✓ sum (4 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.844 s, estimated 1 s
Ran all test suites.