【问题标题】:How do you mock/test requestjs requestcallback with Jest你如何用 Jest 模拟/测试 requestjs requestcallback
【发布时间】:2019-01-12 01:34:39
【问题描述】:

我正在使用 requestjs 向 API 发出 get 请求,然后在 requestCallBack 中将正文映射到自定义 json 对象。我正在尝试使用 Jest 测试此代码,但无论我如何模拟它,它似乎都不起作用

我已经尝试过request.get.mockImplementation(),这似乎只是模拟 get 并且不允许我测试回调中的代码

    await request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) })
    jest.mock('request')
    jest.mock('request-promise-native')

    import request from 'request-promise-native'

    test('test requestCallback code', async () => {
        // not sure how to test that bodyTransformer is called and is working
    }

【问题讨论】:

    标签: javascript jestjs restify request-promise requestjs


    【解决方案1】:

    您可以使用 mockFn.mock.calls 获取调用模拟的参数。

    在这种情况下request.get 是一个模拟函数(因为整个request-promise-nativeauto-mocked),因此您可以使用request.get.mock.calls 来获取调用它的参数。第三个参数将是您的回调,因此您可以检索它,然后像这样测试它:

    jest.mock('request-promise-native');
    
    import request from 'request-promise-native';
    
    test('test requestCallback code', () => {
      request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) });
    
      const firstCallArgs = request.get.mock.calls[0];  // get the args the mock was called with
      const callback = firstCallArgs[2];  // callback is the third argument
    
      // test callback here
    });
    

    【讨论】:

    • 这太棒了!谢谢布赖恩。另一个问题:我将如何在该回调 IE (req, res, body) => { this.firstName = body.firstName } 中获取和测试参数当我使用您提供的代码时,我似乎总是返回 undefined for body
    • 想通了布赖恩 - 只需要传递我需要的参数。非常感谢您的帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 2020-05-28
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2021-08-27
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多