如何在方法中模拟axios调用?

时间:2019-04-22 19:29:43

标签: vue.js jestjs

我正在尝试在vuejs方法中模拟axios调用。这可能吗?

这是我的Vue组件(SomeObj):

 methods:{
        callAxiosMethod() { 
          const callApi= axios.create();
          callApi.defaults.timeout = 10000;
          callApi.get(mockedUrl)
          .then(response => {
             console.log('response is ' + response);
          })
          .catch(e => {});
        }
    }

这是我的spec.js

let mockData = {};
beforeEach(() => {
        jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve(mockData));
    });

    let wrapper = shallowMount(SomeObj, {
        stubs: [], localVue, mocks: {
            mockUrl: mockUrl,
            $route: {
                params: { testId: "123" }
            }
        }
    });
    it('is a Vue instance', () => {
        expect(wrapper.isVueInstance()).toBeTruthy();
        axios.get.mockResolvedValue(mockData);
        wrapper.vm.callAxiosMethod();
    })

当我查看覆盖范围时,系统显示callApi没有被覆盖。关于如何在函数中模拟axios调用的任何想法?

1 个答案:

答案 0 :(得分:1)

您的代码调用axios.create,因此您需要模拟该函数以返回模拟callApi对象。

这是一个简化的工作示例:

code.js

import * as axios from 'axios';

const mockedUrl = 'http://mock-url';

export const callAxiosMethod = () => {
  const callApi = axios.create();
  callApi.defaults.timeout = 10000;
  return callApi.get(mockedUrl);  // <= return the Promise so it can be awaited
}

code.test.js

import { callAxiosMethod } from './code';

jest.mock('axios', () => ({
  create: jest.fn().mockReturnValue({
    defaults: {},
    get: jest.fn().mockResolvedValue('mocked data')
  })
}));

test('callAxiosMethod', async () => {  // <= async test function
  const response = await callAxiosMethod();  // <= await the Promise
  expect(response).toBe('mocked data');  // Success!
});