0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JestでTypeScriptのテストを書く(Step3:API検証)

Last updated at Posted at 2023-12-31

はじめに

表題通り、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.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?