回调间谍没有在流端调用

时间:2017-09-19 21:15:25

标签: javascript node.js stream tdd sinon

我无法理解为什么这不起作用。我有一个模块,它使用native nodejs http模块发送包含一些有效负载的HTTP POST请求。我正在使用sinon对请求方法进行存根,并为请求和响应流传递PassThrough流。

DummyModule.js

const http = require('http');

module.exports = {

    getStuff: function(arg1, arg2, cb) {

        let request = http.request({}, function(response) {

            let data = '';

            response.on('data', function(chunk) {
                data += chunk;
            });

            response.on('end', function() {
                // spy should be called here
                cb(null, "success");
            });

        });


        request.on('error', function(err) {
            cb(err);
        });

        // payload
        request.write(JSON.stringify({some: "data"}));
        request.end();
    }

};

test_get_stuff.js

const sinon = require('sinon');
const http = require('http');
const PassThrough = require('stream').PassThrough;

describe('DummyModule', function() {

    let someModule,
        stub;

    beforeEach(function() {
        someModule = require('./DummyModule');
    });

    describe('success', function() {

        beforeEach(function() {
            stub = sinon.stub(http, 'request');

        });

        afterEach(function() {
            http.request.restore()
        });

        it('should return success as string', function() {
            let request = new PassThrough(),
                response = new PassThrough(),
                callback = sinon.spy();

            response.write('success');
            response.end();


            stub.callsArgWith(1, response).returns(request);

            someModule.getStuff('arg1', 'arg2', callback);

            sinon.assert.calledWith(callback, null, 'success');
        });
    });
});

没有调用间谍,测试因AssertError: expected spy to be called with arguments而失败。因此,response.on('end', ...)不会被调用,因此测试失败。是否需要以某种方式触发响应流上的结束事件?

1 个答案:

答案 0 :(得分:1)

现在正在运作。首先,需要使用emit method发出事件。 其次,事件需要在someModule.getStuff(...)方法调用之后立即发出:

...
someModule.getStuff('arg1', 'arg2', callback);

response.emit('data', 'success');
response.emit('end');

sinon.assert.calledWith(callback, null, 'success');
...