0

I can't get my head around why this is not working. I have a module which sends a HTTP POST request containing some payload using the native nodejs http module. I am stubbing the request method with sinon and pass the PassThrough stream for the request and response streams.

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');
        });
    });
});

The spy does not get called and the test fails with AssertError: expected spy to be called with arguments. So the response.on('end', ...) does not get called and therefore the test failure. Does the end event on the response stream needs to be triggered somehow?

miron
  • 1,361
  • 1
  • 11
  • 24

1 Answers1

1

It's working now. First, the events need to be emitted using the emit method. Second, the events need to be emitted right after the someModule.getStuff(...) method call:

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

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

sinon.assert.calledWith(callback, null, 'success');
...
miron
  • 1,361
  • 1
  • 11
  • 24