Node.js存根request.get()以立即调用回调

问题描述 投票:0回答:1

我正在尝试测试一个在其中调用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()函数的函数。我正在尝试覆盖回调函数的所有分支。我正在尝试不分离回调就实现它...

node.js unit-testing mocha sinon proxyquire
1个回答
0
投票

这里是使用sinonmocha的单元测试解决方案:

© www.soinside.com 2019 - 2024. All rights reserved.