1
2

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 3 years have passed since last update.

【Jest】APIコールする関数をMock化する【TypeScript】

Last updated at Posted at 2021-10-26

Mock化したい関数

例えば、とあるコンポーネントから呼んでいる、下記のようなapiをコールする関数をMock化したいとする

api.ts

export const sampleApi = async (): Promise<AxiosResponse<Sample>> => {
    return axios
        .get('sample/api')
        .then((res) => {
            return res;
        })
        .catch((err) => {
            return err;
        });
};

Let's Mock化!!

index.spec.ts
// ①Mock化したい関数をimportする
import { sampleApi } from 'api';

// ②module全体をMock化する
jest.mock('api');

// ③関数をMock化する
const sampleApiMock = sampleApi as jest.MockedFunction<typeof sampleApi>;

// ④③から任意の値を返すようにしたい場合
sampleApiMock.mockResolvedValue({ status: 200, data: 'hogehoge'});

// ⑤beforeEachなりでResetするのを忘れずに
sampleApiMock.mockClear();

ちなみに、axios自体をmock化したい場合も同じような形でできます

index.spec.ts
// ①
import axios from 'axios';

// ②
jest.mock('axios');

// ③
const axiosMock = axios as jest.MockedFunction<typeof axios>;

参考

モック関数(Jest公式)

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?