Sinon - how to stub nested function?

一笑奈何 提交于 2019-12-03 16:00:21

You are receiving the undefined message because the request variable is unknown within the scope of your test. However, even if you were to correct this and assign the request library to the variable, you would still receive an error as sinon requires a method on any provided object in order to create a stub.

The consequence of such is that the request function itself cannot be stubbed as it does not exist on an object but as a function onto which other methods are defined. In order to support testability, therefore, it'd be preferable to forgo using request directly in your code, and instead use its attached methods which can then be stubbed. For example:

my_app.js

MyModule.prototype.getTicker = function(callback) {
  request.get('http://example.com/api/ticker', function(error, response) {
    ...
  });
};

my_test.js

var request = require('request');

before(function() {
  sinon.stub(request, 'get').yields(null, JSON.stringify({price: '100 USD'}));
});

it('getTicker function should call request on example ticker', function() {
  mymodule.getTicker();
  request.get.called.should.be.equal(true);
});

(Note that running mocha asynchronously is un-necessary when a stub is synchronous).

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