JavaScriptJestNode.jsTypeScript

JestでTypeScriptのテスト

TypeScript使うなら、テストもちゃんとやりたいよね。 インストール Jestの設定 package.jsonに以下の項目を追加します。 テスト対象コードの追加 テスト対象となるコードを書きます。 名前を入れると、 […]

広告ここから
広告ここまで

TypeScript使うなら、テストもちゃんとやりたいよね。

インストール

$ npm init -y
$ npm i -D jest ts-jest @types/jest typescript

Jestの設定

package.jsonに以下の項目を追加します。

{
  ...
  "scripts": {
    "build": "tsc",
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^23.3.10",
    "jest": "^23.6.0",
    "ts-jest": "^23.10.5",
    "typescript": "^3.2.2"
  },
  "jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "tsConfigFile": "tsconfig.json"
      }
    },
    "testMatch": [
      "**/__tests__/*.+(ts|tsx|js)"
    ]
  }
}

テスト対象コードの追加

テスト対象となるコードを書きます。

$ vim index.ts
export const helloWorld = (name: string): string => `Hello ${name}`

名前を入れると、Hello {YOUR_NAME}と返してくるhelloWorld()関数を用意しました。

テストコードの追加

続いてテストコードを書きます。

$ mkdir __tests__/
$ vim __tests__/index.test.ts
import { helloWorld } from '../index';

test('basic', () => {
  expect(helloWorld('John')).toBe('Hello John');
});

test('Failed', () => {
  expect(helloWorld()).toBe('Hello ');
});

あとはこれでテストを実行すればOKです。

$ npm test
 FAIL  __tests__/index.test.ts
  ● Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    __tests__/index.test.ts:8:10 - error TS2554: Expected 1 arguments, but got 0.

    8   expect(helloWorld()).toBe('Hello John');
               ~~~~~~~~~~~~

      index.ts:5:28
        5 export const helloWorld = (name: string): string => `Hello ${name}`
                                     ~~~~~~~~~~~~
        An argument for 'name' was not provided.

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.622s, estimated 2s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

2つ目のテストがこけました。これは関数側でstringの引数を指定しているのに、テストでは引数を指定していないからですね。

おわりに

こんな要領でJestをつかったTypeScriptのテストが実行できます。–watchオプションをつければwatchモードにもできますので、積極的に使っていきたいところです。

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts