Unit testing promise based code in node.js express route/controller
If your method being tested doesn't return a promise then you can't use the promise syntax in Mocha. You can test your method the same way you'd test any other asynchronous method - with done
as a parameter of it
. Let's say we want to test your handler
function:
var handler = function (req, res, next) { //... User.findAsync(query, null, options).then(function (user) { res.json(user); }).catch(function (e) { next(e); });}
We can write a test as such:
describe("The handler", function(){ it("calls res.json", function(done){ // note the done argument handler({query: {before: 5}, // mock request {json: done} // res.json calls our `done` param of this function function(){ throw new Error("error called"); }); });});
Note that we mocked the request, response and the next
handler. Our mocked response has a json method that lets the test know it is complete (this can be a function if you want to make assertions inside it) and if next
is called instead we throw to signal it's not something that was supposed to happen.