Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cnpatric opened this issue Jan 17, 2022 · 1 comment
Open

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

cnpatric opened this issue Jan 17, 2022 · 1 comment

Comments

@cnpatric
Copy link

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

@ShailyAggarwalK
Copy link

ShailyAggarwalK commented Jul 30, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants