Jaimini Chothwani
Jaimini Chothwani

Reputation: 195

How to test axios api using jest and react testing library?

this is my apis.js where my axios logic is written

import axios from 'axios'

function logSuccess(req, res, next) {
  console.log(req, res)

  next(res)
}

function logError(req, res, e, next) {
  console.log(req, res, e)

  next(e)
}

function getResource(url, onComplete) {
  let _onSuccess = (res) => logSuccess(url, res, onComplete)
  let _onError = (res, e) => logError(url, res, e, onComplete)
  let _onException = (e) => logError(url, null, e, onComplete)

  axios
    .get(url)

    .then((res) => {
      res ? _onSuccess(res) : _onError(res)
    }, _onException)

    .catch(_onException)
}

function postResource(url, data, cancelTokenSource, onComplete) {
  let _onSuccess = (res) => logSuccess(url, res, onComplete)
  let _onError = (res, e) => logError(url, res, e, onComplete)
  let _onException = (e) => logError(url, null, e, onComplete)

  axios
    .post(url, data, { cancelToken: cancelTokenSource.token })

    .then((res) => {
      res ? _onSuccess(res) : _onError(res)
    }, _onException)

    .catch(_onException)
}

const apis = {
  getResource,
  postResource,
}

export default apis

this is my other file where i have called axios functions:

    import apis from '../../commonUtils/apis/apis'

export default class LookingGlassAPIs {
  constructor(params) {
    let { apiRoot } = params

    this.routers = {}
    this.commandRequests = {}

    this.routers.getAll = (...rest) =>
      apis.getResource(apiRoot + 'routers', ...rest)
    this.commandRequests.post = (...rest) =>
      apis.postResource(apiRoot + 'commandRequests', ...rest)
  }
}
 const apiRoot = 'http://127.0.0.1:8080/'

i am new to react i donot know to write test case for axios without hitting api.can any one please help me.url is defined in another file but for reference i have decalred here only . should i use axios.get.mockResolvedValue(data)???Is it right way??

Upvotes: 2

Views: 18855

Answers (2)

Robin Michay
Robin Michay

Reputation: 817

You must mock axios and look if axios methods are called with the right parameters for example.

apis.spec.js

import apis from './apis';

jest.mock('axios'); // This overwrites axios methods with jest Mock
import axios from 'axios';

describe('Test Apis', () => {
    describe('getResource', () => {
        describe('with success', () => {
            const url = 'http://test-url.com';
            const onComplete = jest.fn();
            const data = {};

            beforeEach(() => {
                axios.get.mockResolvedValue(data);
            });

            it('should call axios get with given url', () => {
                getResource(url, onComplete);
                expect(axios.get).toBeCalledWith(url);
            });

            it('should call onComplete callback with response', async () => { // do not forget 'async'
                await getResource(url, onComplete); // notice the 'await' because onComplete callback is called in '.then'
                expect(onComplete).toBeCalledWith(data);
            });
        });
    });
});

You could do the same with the error response and POST method. You could also test your LookingGlassAPIs by mocking your apis.js methods, or again by mocking axios, it depends of your "unit" definition inside your project.

Upvotes: 3

AdriSolid
AdriSolid

Reputation: 2825

As long as the functions you want to test don't return anything, you could test if they throw or no.

You would need to spy your axios methods, mocking a return value (in this case a Promise), something like:

import axios from 'axios';
    
beforeAll(() => {
  axios.get.mockImplementation(() => Promise.resolve('whatever-get'));
  axios.post.mockImplementation(() => Promise.resolve('whatever-post'));
});
    
afterAll(() => {
  jest.clearAllMocks();
});
    
test('get does not throw', () => {
  expect(getResource()).not.toThrow();
});
    
test('post does not throw', () => {
  expect(postResource()).not.toThrow();
});

Upvotes: 0

Related Questions