如何使用Jest在Node.js中模拟异步函数

时间:2020-07-13 07:22:34

标签: javascript node.js unit-testing mocking jestjs

在下面的函数中,我必须模拟httpGet函数,因此应该调用模拟函数而不是调用实际函数并返回值

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

我的测试用例

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

1 个答案:

答案 0 :(得分:0)

对于该函数的模拟,您可以拥有与普通函数相同的jest.fn()

然后,您可以实现自己的Promise返回值,也可以使用笑话的mockResolvedValuemockRejectedValue

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

例如:

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