如何使用Jest

时间:2018-09-11 11:54:36

标签: javascript axios jestjs

如何模拟导出为默认函数的axios

我有使用axios()来概括api请求的api帮助器

api.js

export const callApi = (endpoint, method, data = {}) => {

  return axios({
    url: endpoint,
    method,
    data
  })
  .then((response) => // handle response)
  .catch((error) => // handle error)
};

api.spec.js

import axios from 'axios';
import { callApi } from './api';

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {

    // mock axios()
    jest.spyOn(axios, 'default');

    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios.default).toBeCalledWith({ url: endpoint, method, data});
  });
}); 

结果

Expected mock function to have been called with:
  [{"data": {"foo": "bar"}, "method": "post", "url": "/endpoint"}]
But it was not called.

如果我模拟axios.get()或其他方法,该调用可以正常工作,但不适用于axios()。我不想更改callApi()函数的定义。

如何模拟默认的axios()?我想念什么?

1 个答案:

答案 0 :(得分:8)

直接致电jest.spyOn(axios, 'default')(无axios)时,您不能使用default。将api.js中的实现更改为axios.default(...args)即可通过测试。


您可以进行的潜在更改是使用jest.mock('axios')而不是jest.spyOn

import axios from 'axios';
import { callApi } from './api';

jest.mock('axios');

// Make sure to resolve with a promise
axios.mockResolvedValue();

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {
    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios).toBeCalledWith({ url: endpoint, method, data});
  });
}); 
相关问题