LoginSignup
2
1

More than 3 years have passed since last update.

TypeScriptでaxiosのmockテストを実行するための3つのポイント

Posted at

概要

TypeScript で axios の mock が正常に動かない問題の解決策の1つを共有します。
axios の mock を単純に書いても正常に機能しません。

コードの完全なサンプルは次の repository に置いてあります。
https://github.com/algas/axios-mock-example

TypeScript で axios mock テストを動かす3つのポイント

1) client コードで axios adapter に HTTP を設定する

const httpAdapter = require('axios/lib/adapters/http');
axios.defaults.adapter = httpAdapter;

2) client コードから axios を export する

import axios from 'axios';
export { axios as axiosModule };

3) client から import した axios module を axios-mock-adapter で呼び出す

Jest を使ったテストの例

import { getUser, axiosModule } from 'axios-client-example';
import MockAdapter from 'axios-mock-adapter';

test('mock test getUser', async () => {
  const mock = new MockAdapter(axiosModule);
  const resData = { /* foo: bar */ }; // mock response data
  mock.onGet('/path/to/client').reply(200, resData);
  // write code to test your client
  mock.reset();
});

もし client と test を同じパッケージ内で使う場合には axios の import, export は不要です。

まとめ

axios adapter に HTTP を設定して axios-mock-adapter を使うことで TypeScript で axios mock のテストが実施できます。
もっといい方法を知ってる場合にはぜひコメントをいただけるとうれしいです。

2
1
1

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