【问题标题】:How can I mock axios API calls? with using jest如何模拟 axios API 调用?开玩笑
【发布时间】:2020-03-15 00:10:11
【问题描述】:

您好,我正在测试我的 vuex 操作异步函数,该函数通过 axios 调用 api,但我有一些问题,它显示像这样的错误“ 类型错误:无法解构“未定义”或“空”的属性 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)
  })

})

【问题讨论】:

    标签: javascript reactjs vue.js jestjs axios


    【解决方案1】:

    你使用了jest.mock('axios'),它会自动为模块生成模拟,它会为axios.get创建jest.fn(),但除非你另有说明,否则它将返回undefined

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

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

    或简写:

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

    同时检查this answer

    【讨论】:

    • 但它一直向我显示像这样的错误 TypeError: _axios.default.get.mockResolvedValue is not a function..
    • @Erika 可能是因为你删除了jest.mock('axios');
    【解决方案2】:

    我正在使用 jest 和 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' }));
    

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2020-08-16
      • 2021-05-27
      • 2021-11-27
      • 2020-11-18
      相关资源
      最近更新 更多