I am facing a issue while testing my api call with callback functions, service not returning promise it give me response in callback function.
Here is my code.
// UserService.js
addUser(paras, successCallback, failureCallback){
axios.post(URL, params, config)
.then((response) => {
successCallback(response)
})
.catch((error) => {
failureCallback(error)
})
}
// UserComponent.js
const params = {
name: 'jack lee',
email: '[email protected]',
phone: '09909909090'
}
UserService.addUser(
params,
(response) => {
console.log(response)
if(response.success){
toastservice.show('User added')
}
}, (error) => {
console.log(response)
})
Here i try to write test case, but unable to test it correctly.
// UserComponent.test.js
jest.mock('axios')
if('Should add user', () => {
const params = {
name: 'jack lee',
email: '[email protected]',
phone: '09909909090'
}
const mockResponse = {
success: true
}
axios.post.mockResolvedValue(mockResponse)
UserService.addUser(
params,
(response) => {
expect(response.success).toBe(true)
})
expect(axios.post).toHaveBeenCalledTime(1)
})
when you use
axios.post.mockResolvedValue(mockResponse), it should return a Promise that resolves tomockResponse. The addUser function is asynchronous. You need to return a Promise from your test to properly handle this. Also there is a typoif('test name' ...)that'stest('test name')