As of Mocha 1.18.0 you can return a promise from a test and the test will pass if the promise is fulfilled or fail if the promise is rejected.
Versions used below
The basic pattern is
Things to note here
- Test function does not declare a
doneparameter like it would if this used callbacks
- The promise from
Verify a fulfilled promise
You can assert all you want inside the fulfill handler. Errors thrown by the fulfill handler cause the resulting promise to be rejected. That’s fine, the test should fail if any of its asserts fail.
Verify a rejected promise
When the code-under-test is expected to return a rejected promise, the promise can’t be returned directly to Mocha or the test will fail.
By specifying a reject handler in the
then call, the error is “caught”, the resulting promise is fulfilled and the test passes.
Asserts are fine in the reject handler because if they fail, an Error is thrown and the resulting promise will be rejected.