React Axios API call test with callback

65 Views Asked by At

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

There are 1 best solutions below

2
DineshMsd On

when you use axios.post.mockResolvedValue(mockResponse), it should return a Promise that resolves to mockResponse. The addUser function is asynchronous. You need to return a Promise from your test to properly handle this. Also there is a typo if('test name' ...) that's test('test name')

// UserService.js
addUser(paras) {
  return new Promise((resolve, reject) => {
    axios
      .post(URL, params, config)
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

 // UserComponent.test.js
import UserService from './UserService';
import axios from 'axios';

jest.mock('axios');

it('Should add user', async () => {
  const params = {
    name: 'jack lee',
    email: '[email protected]',
    phone: '09909909090',
  };

  const mockResponse = {
    success: true,
  };

  axios.post.mockResolvedValue(mockResponse);

  const response = await UserService.addUser(params);

  expect(response.success).toBe(true);
  expect(axios.post).toHaveBeenCalledTime(1);
});