Creating request stub with sinon in mocha

蹲街弑〆低调 提交于 2019-11-30 17:07:50

Although request is a great library, it is not a good example of well structured API. And because module request is defined as a function with additional methods (similarly like express), as what I know you can't create stub for function request with sinon.

The best thing you can do is to avoid to use request function in your code and use only request.get, request.post, etc., which you can easily stub.

Creating stub for Request in your second example doesn't help because Request is not a method, see source code.

Bianca

If anyone is still looking for an answer for this, it looks like you can create a stub for request using sinon:

before(function(done){
  sinon
    .stub(request, 'get')
    .yields(null, null, JSON.stringify({login: "bulkan"}));
  done();
});

more details can be found here

Another workaround would be generating a stub using sinon module and the request dependency in the corresponding module can be overridden using proxyquire.

var sinon = require('sinon');
var proxyquire = require('proxyquire');

describe('something', function(){
  var request;
  var overriddenModule;
  before(function(){
    request = sinon.stub();
    // overriding the 'request' dependency with the stub
    overriddenModule = proxyquire('path_to_module_using_request', {'request': request});     
  });
  it("should do something",function(done){
    // stubbing the request(options,callback) method
    request.withArgs(sinon.match.any,sinon.match.any).yields(null,null,responseBody);
    overriddenModule.method_which_is_doing_request;
    // our logic and assertions before calling done()
  });  
});

For more info, check this article on Unit Testing with Mocks in Node

P Walker

As mentioned in one of the answers to the question How to mock request and response in nodejs to test middleware/controllers?, the node-mocks-http package provides a way to build request and response mocks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!