Last active
May 14, 2019 18:28
-
-
Save BoyCook/5274570 to your computer and use it in GitHub Desktop.
Integration testing a node.js web app with Mocha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?