簡體   English   中英

使用sinon和mocha測試node.js http.get

[英]Using sinon and mocha to test node.js http.get

假設我有以下功能

'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進行存根。

目前,我正在對Facebook做一個真正的http.get ,但我想避免這樣做。

這是我目前的測試:

'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之外的其他東西的情況下,我如何才能實現自己想要的? (我不想使用請求模塊來執行獲取,或使用另一個測試庫)

謝謝!

您應該只用sinon.stub(http, 'get').yields(fakeStream);就能做到這一點sinon.stub(http, 'get').yields(fakeStream); 但查看nock和/或rewire可能會更好地為您服務。 nock會讓您偽造facebook響應,而不會在getLikes實現細節中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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM