【问题标题】:How to mock an async function in nodejs using jest如何使用 jest 在 nodejs 中模拟异步函数
【发布时间】:2022-02-21 03:54:33
【问题描述】:

在下面的函数中,我必须模拟 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);
    })
})

【问题讨论】:

  • 一个异步函数只是一个返回一个承诺的函数,你可以用例如模拟它jest.fn(): jestjs.io/docs/en/…

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


【解决方案1】:

您可以将 jest.fn() 用作函数的模拟,就像普通函数一样。

那么你既可以实现自己的 Promise 返回值,也可以使用 jests 的 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);
    })
})

【讨论】:

  • 它不工作我无法调用模拟函数@Tamas Kuzdi
  • 你尝试了什么@SunnySonar?请发布一些代码sn-p
【解决方案2】:

我会将此模拟为 ES6 模块。在你的测试中,把它放在文件的顶部

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

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2022-11-10
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多