はじめに
表題通り、JestでTypeScriptのテストを書きます。
下記StepでJestの学習を進めていきます
Step1: Jest(環境構築から実行まで)
Step2: Jest(Matcherを利用する)
Step3: Jest(API検証)←今回はここ
Step4: Jest(StubとMockとSpy)
API通信
ディレクトリ構成
~/develop/react/jest_ts$ tree -I node_modules
.
├── jest.config.js
├── package.json
├── src
│ ├── __tests__
│ │ ├── api.test.ts
│ │ ├── sample.test.ts
│ │ └── sum.test.ts
│ ├── api.ts
│ └── sum.ts
├── tsconfig.json
└── yarn.lock
3 directories, 9 files
src/api.ts
import axios from 'axios';
export const fetchData = async (url) => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
throw error;
}
};
src/__tests__/api.test.ts
import axios from 'axios';
import { fetchData } from '@/api';
// axios.get を手動でモックに設定
axios.get = jest.fn();
describe('fetchData', () => {
it('fetches successfully data from an API', async () => {
// mockを準備
const data = { data: 'some data' };
(axios.get as jest.Mock).mockResolvedValue({ data });
await expect(fetchData('https://example.com')).resolves.toEqual(data);
});
it('fetches erroneously data from an API', async () => {
// mockを準備
const errorMessage = 'Network Error';
(axios.get as jest.Mock).mockRejectedValue(new Error(errorMessage));
await expect(fetchData('https://example.com')).rejects.toThrow(
errorMessage
);
});
});
実行結果
テスト実行
~/develop/react/jest_ts$ yarn test api.test.ts
yarn run v1.22.19
$ jest api.test.ts
ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
PASS src/__tests__/api.test.ts
fetchData
✓ fetches successfully data from an API (2 ms)
✓ fetches erroneously data from an API (2 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.599 s, estimated 1 s
Ran all test suites matching /api.test.ts/i.
✨ Done in 1.15s.