繁体   English   中英

如何使用 jest 在 nodejs 中模拟异步 function

[英]How to mock an async function in nodejs using jest

在下面的 function 中,我必须模拟 httpGet function,所以与其调用实际的 function 并返回值,不如调用模拟的 function

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

您可以拥有与模拟 function 相同的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);
    })
})

我会嘲笑它作为一个 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 */ })
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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