回调间谍不会在流结束时被调用

Callback spy does not getting called on stream end

我不明白为什么这不起作用。我有一个模块,它使用本机 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', ...) 不会被调用,因此测试失败。是否需要以某种方式触发响应流上的结束事件?

现在可以使用了。首先,需要使用 emit 发出事件。 其次,需要在 someModule.getStuff(...) 方法调用后立即发出事件:

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

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

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