Let's say I have a function that does something along those lines (where userService.createUser() returns a promise):
userService.createUser(userInfo)
.then(function(){res.json({message: "User added successfully"})})
.fail(function(error){res.send(error)})
.done();
How can I test that, when the promise resolves, res.json() is called, and when the promise rejects, res.send(error) is called?
I have tried writing a test like this:
const anError = new Error();
userService.createUser = sinon.stub().returns(Q.reject(anError));
userController.createUser(request, response);
expect(response.send).to.be.calledWith(anError);
But the test fails with "response.send is never called". I also tried logging something before calling res.send(error) and the logging does happen.
My guess is that expect() is called before res.send(error) is executed since it's asynchronous.
I'm fairly new with promises and unit tests, is it something with my architecture or my use of promises?
I'm using Q for promises and mocha, chai, sinon for my unit tests.
Aucun commentaire:
Enregistrer un commentaire