3
4

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

moxiosを使用してREST-APIのテストコードを書く

3
Posted at

Jestでテストコードを書くときにmockを作ってテストするケースが多いですね。
この記事ではHTTPクライアントのaxiosを使ってREST-APIを実行したときのテストコードについて書きます。

install

$ yarn add axios
$ yarn add -D moxios // moxiosはdevDependenciesで管理

React

  • callback関数を書いています
  • APIのdataを取得したらdispatchでpayloadにdataを渡しています
sammple.js
import axios from 'axios';

React.useEffect(() => { hoge(foo) }, [])

const hoge = async (callback) => {
  const response = await axios.get('http://localhost:3030');
  callback(response.data);
}

const foo = (data) => dispatch({ type: "FUGA", payload: data });

Jest

  • axiosのmock「moxios」を使ってdummyのrequest/responseを記述
  • test前にmoxiosをinstallして終わるとunistallする
  • testコードはasync/awaitで記述
  • moxios.waitのコールバック関数にrequest/responseの記述
sample.test.js
import moxios from 'moxios';

describe('moxios tests', () => {
  beforeEach(() => {
    moxios.install();
  });
  afterEach(() => {
    moxios.uninstall();
  });

  test('calls hoge callback on axios response', async () => {
    const dummy = 'dummy';

    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request.respondWith({
        status: 200,
        response: dummy,
      });
    });

    const mock = jest.fn();
    await hoge(mock);

    expect(mock).toHaveBeenCalledWith(dummy);
  });
});
3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?