简体   繁体   中英

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);
    })
})

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);
    })
})

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 */ })
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM