TypeScriptでユニットテストを書く
TypeScriptで作ってみるシリーズの作業ログです。
今回はユニットテストを書きます。
前回はこちらです。
使用モジュール
- sinon
- @types/sinon
テストダブルを用意するためのツールと型定義です。
インストール方法
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'. */
target
がes5
だと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通信による不安定なテストからスタブによる安定したテストに変えています。
結果