如何模拟axios API调用?开玩笑

时间:2019-11-19 12:55:09

标签: javascript reactjs vue.js jestjs axios

您好,我正在测试通过axios调用api的vuex动作异步功能,但是我遇到了一个问题,即它显示了如下错误:     TypeError:无法解构“未定义”或“空”属性data

  35 |     commit('storeSearchValue', name);
  36 |     const url = process.env.VUE_APP_URL_API_News + '/news' + '?q=' + name;
> 37 |     const { data } = await axios.get(url);"

我的vue js代码是

 async updateSearchValue({ commit }, name) {
    commit('storeSearchValue', name);
    const url = process.env.VUE_APP_URL_API_News + '/news' + '?q=' + name;
    const { data } = await axios.get(url);
    commit('storeNewsData', data.result);
  },

这是测试文件,

import actions from '@/store/modules/data/data-actions.js'
import VueRouter from 'vue-router';
import axios from 'axios';

import {
  createLocalVue
} from '@vue/test-utils';
const localVue = createLocalVue();
localVue.use(VueRouter);
jest.mock('axios');

describe('', () => {
  test('updateSearchValue', async () => {
    const commit = jest.fn()
    const name = jest.fn()

    await actions.updateSearchValue({
      commit,
      name
    })

    expect(commit).toHaveBeenCalledWith('updateSearchValue', name)
  })

})

2 个答案:

答案 0 :(得分:2)

我正在与玩笑和TS合作,并试图做到:

axios.get.mockReturnValue...

或:

axios.get.mockImplementationOnce...

返回以下错误:

TypeError: mockedAxios.get.mockImplementationOnce is not a function

最终对我有用的东西是:

import axios from 'axios';

jest.mock('axios');

axios.get = jest.fn()
            .mockImplementationOnce(() => Promise.resolve({ data: 'mock data' }));

答案 1 :(得分:0)

您已经使用了jest.mock('axios'),它会自动为模块生成模拟,它将为jest.fn()创建axios.get,但是除非您另行通知,否则它将返回undefined

由于您期望它返回带有data属性的对象的已解决承诺,因此可以使用:

axios.get.mockReturnValue(Promise.resolve({
  data: 'mock data'
});

或简写:

axios.get.mockResolvedValue({ data: 'mock data' });