node.js - How to test promise in mocha -
we know when return promise in mocha, test promise.
but if throw exception in promise, how tell if exception throw. say, if exception throw in promise, test passes.
it("should not take game code same user twice", function (done) { return gamegiftmanage.takegamecode(gamegiftid, userid) .catch(function (e) { expect(e).to.exist; done(); }) })
this test used test exception, won't work in cases.
takegamecode:
takegamecode: function (giftid, userid) { return gamegiftcode.count({gift: giftid, user: userid}).exec().then(function (c) { if (c) { throw '该用户已经领取过礼包'; } }).then(function () { return gamegiftcode.findoneandupdate({gift: giftid, user: {$exists: false}}, {user: userid}).exec(); }).then(function (a) { if (!a) { throw '礼包领完了'; } else { return a; } }); },
instead of using throw, use reject when error occurs in promise. that's there for. triggers .catch() trying assert from.
in addition, sake of keeping things simple, it's not recommended reject() (which saying throw undefined). reject(new error('something meaningful here') produce more consistent results , better test suite everytime.
heres great article go bit more in depth of whats , whys http://making.change.org/post/69613524472/promises-and-error-handling
edit: posted context , looks within usage of mongoose, docs have pretty example of how handle errors when using promises. instead of using .catch(), thrown error passed second param .then() see this link
so instead of .catch(), want
.then(null, function(error){ //handle assertion })