How can I cover Axios-retry failure unit testing using Mocha chai Nodejs?

574 views Asked by At

How can we unit test the following code (axios-retry logic)

AxiosRetryClass.ts

import { AxiosInstance, AxiosRequestConfig } from 'axios';
import axiosRetry from 'axios-retry';


export class AxiosRetryClass {
    constructor() {
    }

   public async callAxios(axiosConfig: AxiosRequestConfig): Promise<any> {
       const instance = new AxiosSession().getAxiosInstance();
    
          axiosRetry(instance, {
            retries: 3,
            retryCondition: (error: any) => {
                return error.response.status === 500;
            },
            retryDelay: (count: number, err: any) => {
                    return 1 * 60 * 1000;
            },
        });

      let response = { status: 0};
      try {
        response =  await instance(axiosConfig);

      } catch (error: any) {
        response = error;
        console.log(`AxiosClass: call error ${error}`);
       }

      return response;
    }
   
  }

AxiosSession.ts

import {HttpsCookieAgent, HttpCookieAgent } from 'http-cookie-agent';
import { CookieJar } from 'tough-cookie';
import axios from 'axios';

export class AxiosSession {
   constructor() {}

 public getAxiosInstance(): Promise<any> {
    const agents = {
             httpAgent: new HttpCookieAgent({ new CookieJar(), true }),
             httpsAgent: new HttpsCookieAgent({ new CookieJar(), true }),
        }

    const instance = axios.create(agents);

    return instance;
   }
 }

AxiosRetry.spec.ts

import Axios, { AxiosInstance } from 'axios';
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe(‘AxiosClassTest ', () => {
   let sinonStub: sinon.SinonSandbox;

   beforeEach(() => {
    sinonStub = sinon.createSandbox();
   });

it(‘Test Axios retry’, async () => {
    let instance = {} as AxiosInstance;

    instance.get = sinonStub.stub().rejects({status: 500}); //Tried both returns and rejects

    const session = new AxiosSession();
    session.getAxiosInstance = sinonStub.stub().returns(instance);

    const axiosClass = new AxiosClass();
    const url = `dummy-error-url`

     await axiosClass.callAxios({ url, method: ‘GET’ });


    });
});

Note: Test case is running successfully. But axios-retry code not covered. I mean the below code

       axiosRetry(instance, {
            retries: 3,
            retryCondition: (error: any) => {
                return error.response.status === 500;
            },
            retryDelay: (count: number, err: any) => {
                    return 1 * 60 * 1000;
            },
        });
0

There are 0 answers