lundi 23 février 2015

How to test asychronous errors?

I am using mocha and should to test a simple spike node server.



exports.start = function(portNumber, htmlFilePath) {
if(!portNumber) throw new Error('No port number has been passed.');

server = http.createServer();

server.on('request', function(request, response) {
if(request.url === '/') {
if(!htmlFilePath) throw new Error('No html file path has been passed.');

fs.readFile(htmlFilePath, function (err, data) {
response.end(data);
});
} else {
response.statusCode = 404;
response.end();
}
});

server.listen(portNumber);
};


How would I go about testing that when the request url is "/" and that no htmlFilePath was passed it should throw an error?



it('should throw an error if no html file path was passed and asked for "/"', function(done) {
server.start(PORT_NUMBER);
(function() {
http.get('http://localhost:' + PORT_NUMBER, function() {
done();
});
}).should.throw();
});


This test does not pass, as the error is thrown asynchronously:



AssertionError: expected [Function] to throw exception


Any ideas?


Aucun commentaire:

Enregistrer un commentaire