Skip to content

Instantly share code, notes, and snippets.

@BoyCook
Last active May 14, 2019 18:28
Show Gist options
  • Save BoyCook/5274570 to your computer and use it in GitHub Desktop.
Save BoyCook/5274570 to your computer and use it in GitHub Desktop.
Integration testing a node.js web app with Mocha
var http = require('http');
var server = undefined;
function HttpServer(config) {
this.port = config.port;
}
HttpServer.prototype.start = function (fn) {
server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({ data: 'Some data'}));
}).listen(this.port, fn);
console.log('Server started at [%s]', this.port);
return this;
};
HttpServer.prototype.stop = function (fn) {
server.close();
if (fn) {
fn();
}
};
exports.HttpServer = HttpServer;
var should = require('should');
var request = require('request');
var url = 'http://localhost:8080';
var HttpServer = require('./server').HttpServer;
var server;
describe('HttpServer', function () {
before(function (done) {
server = new HttpServer({port: 8080}).start(done);
});
after(function (done) {
server.stop(done);
});
it('should get root ok', function (done) {
request(url, function (error, response, body) {
response.statusCode.should.eql(200);
body.should.eql({ data: 'Some data'});
done();
});
});
});
@ROldford
Copy link

ROldford commented Nov 7, 2017

I've tried using this, and the test fails with:
Uncaught AssertionError: expected '{"data":"Some data"}' to equal Object { data: 'Some data' }

Shouldn't the test parse the JSON string from the body?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment