1. ホーム
  2. javascript

[解決済み] Jestでaxiosをテストするにはどうしたらいいですか?

2022-08-30 04:56:23

質問

Reactでこのようなアクションがあります。

export function fetchPosts() {
    const request = axios.get(`${WORDPRESS_URL}`);
    return {
        type: FETCH_POSTS,
        payload: request
    }
}

どのようにすれば アクシオス をテストするにはどうしたらよいでしょうか?

Jestのサイトでは、非同期コードでモック関数を使用するこの使用例がありますが、Axiosでこれを行うことは可能でしょうか?

参考にしてください。 非同期の例

ここまでやって、正しい型を返していることをテストしています。

it('should dispatch actions with the correct type', () => {
    store.dispatch(fetchPosts());
    let action = store.getActions();
    expect(action[0].type).toBe(FETCH_POSTS);
});

モックデータを渡して、それが返ってくるかどうかテストするにはどうしたらよいでしょうか?

どのように解決するのですか?

私は アクシオスモックアダプタ . この場合、サービスは ./chatbot に記述されています。 モックアダプターでは、APIエンドポイントが消費されたときに何を返すかを指定します。

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

この例の全体像は、こちらで見ることができます。

サービス https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

テスト https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js