【问题标题】:How to unitest npm `request.post` using jest如何使用 jest 统一 npm `request.post`
【发布时间】:2021-06-08 01:29:22
【问题描述】:

我正在使用npm request,如何模拟 request.post 我需要测试错误场景,statuscode not 200 场景和成功流程。

1 request.post(reqObject, (error: Error, response: any, body: any) => {
2     if (error) { return reject(error); }
3     if (response.statusCode !== 200) {
4         return reject('Invalid status code <' + response.statusCode + '>');
5     }
6     return resolve(JSON.parse(body));
7 });

【问题讨论】:

  • 我建议不要嘲笑你不拥有的东西,比如请求。这样一来,当您使用更多界面时,您的模拟就会变得更加复杂(例如,参见stackoverflow.com/a/65130857/3001761),甚至发现您对如何使用它有误(参见例如stackoverflow.com/a/65627662/3001761)。引入一个外观来模拟,或者使用mswnock 之类的东西在传输层进行测试。

标签: node.js npm jestjs


【解决方案1】:

request 对象可以被jest.mock('request') 模拟。

类似这样的:

const request = require("request");
jest.mock('request', () => {
    return {
        post: () => { 
            console.log("mocked"); 
            // or something like jest.fn()
        }
    };
});

test('test description', () => {
    // request.post within fetchData has been mocked
    // await fetchData(); 
});

【讨论】:

  • 谢谢@lastr2d2 如果我模拟帖子,我该如何测试如何测试第 2 到第 6 行?
  • 您将定义 post mock 的参数以包含(并随后调用)带有您要测试的值的回调。
  • 这里是一个示例模拟函数post: (req, callback) =&gt; { let err = null; let response = {statusCode: 200}; let body = {}; callback(err, response, body); }
猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多