繁体   English   中英

如何使用 Jest 模拟 Axios 作为默认导出

[英]How to mock Axios as default export with Jest

如何模拟导出为默认函数的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() 我错过了什么?

直接调用axios时不能使用jest.spyOn(axios, 'default') (无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});
  });
}); 

对于jest 28 ,至少,您可以使用以下内容:

import axios from 'axios'
import { myModule } from '.'

jest.mock('axios')
const mockedAxios = jest.mocked(axios, true)

describe('myModule', () => {
  test('response with no errors', async () => {
    mockedAxios.mockReturnValue('SUCCESS' as any)
    ...

    expect(mockedAxios).toHaveBeenCalledWith({
      URL: 'http://....',
      data: { update: 'data' },
      method: 'PUT',
      ...config
    })
  })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM