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

标签 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 = '';
        // 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 测试它,但我不知道如何 stub 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();
        });
    });

});

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

谢谢!

最佳答案

你应该能够用 sinon.stub(http, 'get').yields(fakeStream); 做到这一点,但你可能通过查看 nock 得到更好的服务和/或 rewire . 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()

关于node.js - 使用 sinon 和 mocha 测试 node.js http.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28139077/

相关文章:

javascript - Babel [karma-babel-preprocessor] 不为 Karma 测试转换 ES6->ES5

javascript - 如何通过 Hardhat 测试 RSK 测试网部署的智能合约?

javascript - 将 NodeJs 导入 TypeScript 编译错误

c# - 进入/退出方法时如何增加/减少缩进?

testing - 如何检查线程组在jmeter中停止执行

ruby-on-rails - rails 3 : How to test router scope?

javascript - Node.JS 传输数据

javascript - 表之间的序列化和查询

node.js - Node 异步与同步

javascript - 如何在sinon js中测试设置的Interval