javascript - 回调 spy 不会在流结束时被调用

标签 javascript node.js stream tdd sinon

我不明白为什么这不起作用。我有一个模块,它使用 native Nodejs http 模块发送包含一些有效负载的 HTTP POST 请求。我使用 sinon 来 stub 请求方法,并传递请求流和响应流的 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');
        });
    });
});

spy 不会被调用,并且测试失败,并显示AssertError:期望使用参数调用 spy 。因此 response.on('end', ...) 不会被调用,因此测试失败。响应流上的结束事件是否需要以某种方式触发?

最佳答案

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

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

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

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

关于javascript - 回调 spy 不会在流结束时被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309850/

相关文章:

javascript - 将 JSON 数据从 php 传递到 html-data 属性,然后传递到 Javascript

Javascript : eliminate array element with two array

javascript - node.js win10 puppeteerexecutablePath 字符串

java - 如何在Java中使用对象的ID和LocalDateTime字段正确过滤列表?

java - 通过 HTTP SSL 的流未被刷新

node.js - 将请求流中的文件存储在node.js中

javascript - 让 Html.Raw 在 MVC Razor Javascript 的 if 语句中工作?

javascript - 在 Bootstrap 模式中错误地显示 d3.js

javascript - 如何在 javascript 中打印具有固定列宽的二维数组?

javascript - 一旦将 angular2 应用程序与 gulp 捆绑在一起,如何在 apache http 服务器上进行部署