Reputation: 83
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)
})
})
Upvotes: 4
Views: 20919
Reputation: 32158
You have used jest.mock('axios')
which is automatically generating mock for module and it will create jest.fn()
for axios.get
, but it will return undefined
unless you tell it otherwise
Since you're expecting it to return a resolved promise with object with data
property you can use:
axios.get.mockReturnValue(Promise.resolve({
data: 'mock data'
});
or the short-hand:
axios.get.mockResolvedValue({ data: 'mock data' });
Upvotes: 5
Reputation: 53525
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' }));
Upvotes: 8