6

I'm trying to mock request and response objects for my node/express handlers. I've tried a few mocking libraries and have run into issues with API compatibility, which has made them too unreliable for testing purposes.

What I would like to do is create the raw request and response objects myself and direct the output somewhere other than a live connection.

Here's what I have so far:

env.mockReq = function(o){
    o = o || {};
    o.hostname = 'www.tenor.co';
    o.protocol = 'https';
    o.path = o.url;
    o.createConnection = function(){
        console.log('mockReq createConnection');
    };
    var req = new http.ClientRequest(o);
    req.url = o.url;
    req.method = o.method;
    req.headers = o.headers || {};
    return req;
};
env.mockRes = function(o){
    var res = new http.ServerResponse({
        createConnection: function(){
            console.log('mockRes createConnection');
        }
    });
    return res;
};

Here's some test code:

var req = env.mockReq({method: 'GET', url: '/'});
var res = env.mockRes();


res.on('end', function(arguments){
    expect(this.statusCode).toBe(200);
    expect(this._getData().substr(-7)).toEqual('</html>');
    scope.done();
    done();
});

// my express app
app.handle(req, res);

My handler is piping a stream data source to the response:

stream.pipe(response);

It works fine when I load the requests in a browser, but my test times out because the response end event never gets fired. I should note that I have logging statements in my handler that's under test and it completes right to the end.

To complicate matters, I'm using nock to mock out some API requests. I had to add the following to prevent an error:

// Prevents "Error: Protocol "https" not supported. Expected "http:""

nock('http://www.example.com')
.persist()
.get('/non-existant-path')
.reply(function(uri, requestBody) {
    console.log('nock path:', this.req.path);
    return ''
});

That nock callback never actually gets called though. But without this code I get that error, even if I don't use https. The live version of my site redirects all traffic to https, so maybe a live connection is being made, but then why is my handler executing?

Seán Hayes
  • 4,060
  • 4
  • 33
  • 48

0 Answers0