我正在尝试测试一个在其中调用request.get()
函数的函数。我正在尝试覆盖回调函数的所有分支。我试图在不将回调函数分离到其他函数的情况下实现它,因为它使用上一个闭包的变量。]>
这里是一个例子说明。foo.js:
var request = require('request'); function func(arg1, arg2) { request.get({...}, function(error, response, body) { // do stuff with arg1 and arg2 // want to be covered if (...) { // want to be covered ... // want to be covered } else if (...) { // want to be covered ... // want to be covered } else { ... // want to be covered } }); } exports.func = func;
我试图用sinon和proxyquire进行存根。
foo.spec.js(存入sinon):
var foo = require('./foo'), var sinon = require('sinon'), var request = require('request'); var requestStub = sinon.stub(request, 'get', function(options, callback) { callback(new Error('Custom error'), {statusCode: 400}, 'body'); }); // Trying to replace it with a function that calls the callback immediately so not to deal with async operations in test foo.func(5, 3);
foo.spec.js(以proxyquire开头):
var requestStub = {}; var proxyquire = require('proxyquire'), var foo = proxyquire('./foo', {'request': requestStub}), var sinon = require('sinon'); requestStub.get = function(options, callback) { callback(new Error('Custom error'), {statusCode: 400}, 'body'); }; // Trying to replace it with a function that calls the callback immediately so not to deal with async operations in test foo.func(5, 3);
都没有工作。当我尝试调试时,我从未遇到过回调函数,这表明我没有对
request.get()
方法进行正确的存根处理,从而仍然使它仍然异步运行。我会很高兴有人告诉我在两种情况下(sinon和proxyquire)我做错了什么,以及有关如何解决它的示例。
我正在尝试测试一个在其中调用request.get()函数的函数。我正在尝试覆盖回调函数的所有分支。我正在尝试不分离回调就实现它...
这里是使用sinon
和mocha
的单元测试解决方案: