Skip to content

Instantly share code, notes, and snippets.

@chmanie
Last active July 27, 2019 18:52
Show Gist options
  • Save chmanie/da3c150cc8fda254a1a5 to your computer and use it in GitHub Desktop.
Save chmanie/da3c150cc8fda254a1a5 to your computer and use it in GitHub Desktop.
Async testing with node-http-mocks
'use strict';
var EventEmitter = require('events').EventEmitter;
var httpMocks = require('node-mocks-http');
module.exports = {
createRequest: httpMocks.createRequest.bind(httpMocks),
createResponse: function (opts) {
opts = opts || {};
opts.eventEmitter = EventEmitter;
var res = httpMocks.createResponse(opts);
var emit = res.emit;
res.emit = function (evt) {
if (evt === 'end') {
var data = res._isJSON ? JSON.parse(res._getData()) : res._getData();
emit.call(res, 'end', data);
} else {
emit.apply(res, arguments);
}
};
var end = res.end;
res.end = function () {
var args = arguments;
process.nextTick(function () {
end.apply(res, args);
});
};
var json = res.json;
res.json = function () {
json.apply(res, arguments);
res._isJSON = true;
res.end();
};
var redirect = res.redirect;
res.redirect = function () {
redirect.apply(res, arguments);
res.end();
};
return res;
}
};
var httpMocks = require('./async-http-mocks');
var api = require('./api');
var req = httpMocks.createRequest();
var res = httpMocks.createResponse();
it('gets a list of all users in json format', function (done) {
api.getUsers(req, res);
res.on('end', function (body) {
assert.equal(body[0].username, 'foo');
done();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment