Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sinon和mocha测试node.js http.get_Node.js_Testing_Mocha.js_Sinon - Fatal编程技术网

使用sinon和mocha测试node.js http.get

使用sinon和mocha测试node.js http.get,node.js,testing,mocha.js,sinon,Node.js,Testing,Mocha.js,Sinon,假设我有以下函数 'use strict'; var http = require('http'); var getLikes = function(graphId, callback) { // request to get the # of likes var req = http.get('http://graph.facebook.com/' + graphId, function(response) { var str = ''; //

假设我有以下函数

'use strict';
var http = require('http');

var getLikes = function(graphId, callback) {
    // request to get the # of likes
    var req = http.get('http://graph.facebook.com/' + graphId, function(response) {
        var str = '';
        // while data is incoming, concatenate it
        response.on('data', function (chunk) {
            str += chunk;
        });
        // data is fully recieved, and now parsable
        response.on('end', function () {
            var likes = JSON.parse(str).likes;
            var data = {
                _id: 'likes',
                value: likes
            };
            callback(null, data);
        });
    }).on('error', function(err) {
        callback(err, null);
    });
};

module.exports = getLikes;
我想用mocha和sinon测试它,但我不知道如何存根
http.get

现在我正在做一个真正的
http.get
到facebook,但我想避免它

以下是我目前的测试:

'use strict';
/*jshint expr: true*/
var should = require('chai').should(),
    getLikes = require('getLikes');

describe('getLikes', function() {

    it('shoud return likes', function(done) {
        getLikes(function(err, likes) {
            should.not.exist(err);
            likes._id.should.equal('likes');
            likes.value.should.exist();
            done();
        });
    });

});
我怎样才能实现我想要的,而不依赖于西农以外的东西?(我不想使用请求模块执行get,也不想使用其他测试库)


谢谢

您应该能够使用sinon.stub(http,'get').yields(fakeStream)实现这一点但通过查看和/或,您可能会得到更好的服务
nock
可以让你伪造facebook的响应,而不会在
getLikes
实现细节中弄脏太多东西
rewire
将允许您在模拟
http
变量中交换到
getLikes
范围中,而无需对
http.get
函数进行全局修补

如上所述,只需使用sinon即可,您将需要创建一个与流完全相似的模拟响应。比如:

var fakeLikes = {_id: 'likes', value: 'foo'};
var resumer = require('resumer');
var stream = resumer().queue(JSON.stringify(fakeLikes)).end()

我尝试了你的解决方案,但mocha告诉我done()被调用了两次,我不明白。但是当我将存根放在一个before中时,我得到了一个
类型错误:无法调用未定义的
的方法“on”。这让我快发疯了。