首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jest模拟/测试requestjs requestcallback

如何使用Jest模拟/测试requestjs requestcallback
EN

Stack Overflow用户
提问于 2019-01-11 00:37:47
回答 1查看 1.1K关注 0票数 1

我使用requestjs向API发出get请求,然后在requestCallBack中将主体映射到自定义的json对象。我试着用Jest测试这段代码,但不管我怎么嘲弄它,它似乎都不起作用

我尝试过request.get.mockImplementation(),这似乎只是在嘲笑get,而不允许我在回调中测试代码

代码语言:javascript
复制
    await request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) })
代码语言:javascript
复制
    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
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-11 01:05:07

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

在本例中,request.get是一个模拟函数(因为整个request-promise-native自动嘲弄),所以您可以使用request.get.mock.calls来获取调用它的参数。第三个参数将是您的回调,因此您可以检索它,然后像这样测试它:

代码语言:javascript
复制
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
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54138867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档