Answer the question
In order to leave comments, you need to log in
How to mock service API in Jest if api().user.getUserName.mockResolvedValueOnce('...') doesn't work?
api().user.getUserName.mockResolvedValueOnce('Alice') call returns
test code error
import MyComponent from '@/views/MyComponent.vue';
import { mount } from '@vue/test-utils';
import api from '@/helpers/api'
import flushPromises from 'flush-promises'
jest.mock('@/helpers/api')
describe('MyComponent.vue', () => {
it('calls api with getMessage and show "Username: Alice"', async () =>{
api().user.getUserName.mockResolvedValueOnce('Alice')
const wrapper = mount(ApiServise)
await flushPromises()
expect( api().user.getUserName ).toHaveBeenCalledTimes(1)
const usernameText = wrapper.find('.username').text()
expect( usernameText ).toEqual('Username: Alice')
})
});
import axios from 'axios';
const MOCK_SERVER = 'https://reqres.in/api'
const user = {
getUserName(id = 2) {
return axios
.get(`${MOCK_SERVER}/users/${id}`)
.then(r => r.data)
.then(r => r.data)
.then(r => r.first_name)
},
}
export default function api(){
return {
user
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question