ash007
ash007

Reputation: 333

How do I mock an async function that makes network request using axios?

I want to unit test a function below that calls an endpoint using axios in my node.js server.

const callValidateCookieApi = async (cookie) => {
  try {
    const config = {
      method: 'post',
      url: process.env.API_COOKIE_VALIDATION,
      headers: {
        Cookie: cookie
      }
    }
    return await axios(config)
  } catch (error) {
    console.log(error.message)
    return error
  }
}

How do I write unit test cases by mocking the axios call that is inside the function?

Upvotes: 1

Views: 2472

Answers (1)

Lin Du
Lin Du

Reputation: 102477

In order to stub axios function, you need an extra package named proxyquire. For more info, see How to use Link Seams with CommonJS

Unit test solution:

index.js:

const axios = require('axios');

const callValidateCookieApi = async (cookie) => {
  try {
    const config = {
      method: 'post',
      url: process.env.API_COOKIE_VALIDATION,
      headers: {
        Cookie: cookie,
      },
    };
    return await axios(config);
  } catch (error) {
    console.log(error.message);
    return error;
  }
};

module.exports = { callValidateCookieApi };

index.test.js:

const proxyquire = require('proxyquire');
const sinon = require('sinon');
const { expect } = require('chai');

describe('64374809', () => {
  it('should pass', async () => {
    const axiosStub = sinon.stub().resolves('fake data');
    const { callValidateCookieApi } = proxyquire('./', {
      axios: axiosStub,
    });
    const actual = await callValidateCookieApi('sessionId');
    expect(actual).to.be.eql('fake data');
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'post',
      url: undefined,
      headers: {
        Cookie: 'sessionId',
      },
    });
  });

  it('should handle error', async () => {
    const mErr = new Error('network');
    const axiosStub = sinon.stub().rejects(mErr);
    const { callValidateCookieApi } = proxyquire('./', {
      axios: axiosStub,
    });
    const actual = await callValidateCookieApi('sessionId');
    expect(actual).to.be.eql(mErr);
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'post',
      url: undefined,
      headers: {
        Cookie: 'sessionId',
      },
    });
  });
});

unit test result:

  64374809
    ✓ should pass (84ms)
network
    ✓ should handle error


  2 passing (103ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

Upvotes: 4

Related Questions