我不明白为什么这不起作用。我有一个模块,它使用 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/