'How to mock an async function in nodejs using jest

In the below function I have to mock httpGet function, so instead of call actual function and returning the value it should call a mock function

getStudents: async(req,classId) => {
  
  let result = await httpGet(req);
  return result;
},

My test case

describe('Mock',()=>{
    it('mocking api',async()=>{
        const result = await getStudents(req,classId);;
        console.log(result);
    })
})


Solution 1:[1]

you can have the same jest.fn() as a mock for the function as you would do for a normal one.

then you can either implement your own Promise return value, or use jests's mockResolvedValue or mockRejectedValue

https://jestjs.io/docs/en/mock-function-api#mockfnmockresolvedvaluevalue

For example:

import { httpGet } from 'http';
jest.mock('http'); // this is where you import the httpGet method from

describe('Mock',()=>{
    it('mocking api',async() => {
        httpGet.mockResolvedValue(mockresult); // httpGet should already be a jest.fn since you used jest.mock
        const result = await getStudents(req,classId);
        console.log(result);
    })
})

Solution 2:[2]

I would mock this as an ES6 module. In your tests, stick this at the top of your file

jest.mock('http', () => {
  const originalModule = jest.requireActual('http')
  return {
    __esModule: true, // necessary to tag this as an ES6 Module
    ...originalModule, // to bring in all the methods
    httpGet: jest.fn().mockResolvedValue({ /* the object you want returned */ })
  }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Igbanam