なになれ

IT系のことを記録していきます

TypeScriptでユニットテストを書く

TypeScriptで作ってみるシリーズの作業ログです。
今回はユニットテストを書きます。

前回はこちらです。

hi1280.hatenablog.com

使用モジュール

  • sinon
  • @types/sinon

https://sinonjs.org/

テストダブルを用意するためのツールと型定義です。

インストール方法

npm install --save sinon
npm install --save @types/sinon

コード

tsconfig.json ※一部抜粋

    "target": "es2015",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */

targetes5だとPromiseの箇所でエラーになってしまったので、es2015に変更しました。

main.spec.ts

import assert = require("assert");
import axios from "axios";
import sinon from "sinon";
import { main } from "../src/main";

describe("main()", () => {
    it("assert response", async () => {
        const resolved = Promise.resolve<any>({
            data: new Array(20),
          });
        sinon.stub(axios, "get").returns(resolved);
        const res = await main();
        assert(res.data.length === 20);
    });
});

axiosによるHTTPレスポンスの部分をスタブに置き換えて、HTTP通信による不安定なテストからスタブによる安定したテストに変えています。

結果

f:id:hi1280:20181205230249g:plain