Reputation: 7433
I'm attempting to use Mocha to write tests for a Node.js API I'm working on. The current tests I'm writing are only interested to see if responses are coming back with the correct status code - they do not care about the response body.
As such, I have written the following test:
Note, this isn't the real test. I've cut out the project-specific stuff. The error does still occur on the code below.
var http = require('http');
var assert = require("assert");
before(function() {
var server = http.createServer(function(req, res) {
res.end();
}).listen(8080);
});
describe("Convenience Functions", function() {
it("should return a 200 status code", function(done) {
http.get("http://localhost:8080", function(res) {
assert.equal(res.statusCode, 200);
res.on('end', function() {
done();
});
});
});
});
Running that test, however, gives me a timeout from Mocha. Mocha defaults to a 2000ms timeout, but I could change that to any unnecessarily high number and it would still timeout.
I've been fighting with this for hours, and have finally found a "fix". If I change the test to:
describe("Convenience Functions", function() {
it("should return a 200 status code", function(done) {
http.get("http://localhost:8080", function(res) {
assert.equal(res.statusCode, 200);
res.on('data', function() { })
res.on('end', function() {
done();
});
});
});
});
the test no longer times out. You will notice that the only difference between these two tests is that the second version is handling the data
event on the response. It doesn't do anything with the data, it just defines a listener on it. Now my test passes with flying colors.
This is an easy enough fix to make, but I'm very confused as to why I need to do this. Shouldn't mocha tests just finish as soon as I call done()
?
Upvotes: 0
Views: 1092
Reputation: 146164
http.get("http://localhost:8080", function(res) {
assert.equal(res.statusCode, 200);
done();
});
That's all you need. The data/end events would only be useful if the response had a body, but it doesn't and in any case you don't care, so just call done()
and ignore the response other than checking it's status code.
Shouldn't mocha tests just finish as soon as I call done()?
Yes, and they do. The problem in your first snippet is the end
event never fires so you don't actually ever call done()
.
Upvotes: 2