aishek / axios-rate-limit

Rate limit for axios
MIT License
236 stars 35 forks source link

Was anyone able to mock this library with Jest? #51

Open cnpatric opened 2 years ago

cnpatric commented 2 years ago

We have a hard time mocking this library, any help would be appreciated.

ShailyAggarwalK commented 1 month ago

Source Code:

import axios from 'axios';
import rateLimit from 'axios-rate-limit';

function fetchData() {
  const http = rateLimit(axios.create(), { maxRequests: 2, perMilliseconds: 1000, maxRPS: 2 }) 
  http.getMaxRPS() // 2
  http.get('https://example.com/api/v1/users.json?page=1').then((response) => {
    if(response.status == 200) {
      return response.data
    }
  }).catch(err => console.error(err));
}

Test Code :

jest.mock("axios-rate-limit", () => () => {
   const mockAxios = () => Promise.resolve({
      "status" : 200,
      "data": { "key": "value" }
    });
   return mockAxios;
});

test("Test backend call", async () => {
   const actualResponse = fetchData();
   expect(actualResponse).toBe({ "key": "value" });
});

Above implementation worked for me. The catch is mocking axios-rate-limit also mocks axios, and I was not able to use actual axios with mockserver. So had to mock axios call as well and it worked.