Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock axios API calls? with using jest

Hi I'm testing my vuex action async function which is calling api via axios, but I have some problem that it show error like this " TypeError: Cannot destructure property data of 'undefined' or 'null'.

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

my vue js code is

 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);
  },

and this is test file,

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)
  })

})

like image 240
Erika Avatar asked Dec 23 '22 20:12

Erika


1 Answers

I'm working with jest and TS and trying to do:

axios.get.mockReturnValue...

or:

axios.get.mockImplementationOnce...

returned the following error:

TypeError: mockedAxios.get.mockImplementationOnce is not a function

The thing that finally did the trick for me was:

import axios from 'axios';

jest.mock('axios');

axios.get = jest.fn()
            .mockImplementationOnce(() => Promise.resolve({ data: 'mock data' }));
like image 176
Nir Alfasi Avatar answered Dec 28 '22 12:12

Nir Alfasi