I'm using Mocha to test an asynchronous function that returns a promise.
What's the best way to test that the promise resolves to the correct value?
I'm using Mocha to test an asynchronous function that returns a promise.
What's the best way to test that the promise resolves to the correct value?
Then 'returns' a promise which can be used to handle the error. Most libraries support a method called
done
which will make sure any un-handled errors are thrown.You can also use something like mocha-as-promised (there are similar libraries for other test frameworks). If you're running server side:
Then at the start of your script:
If you're running client side:
Then inside your tests you can just return the promise:
Or in coffee-script (as per your original example)
Mocha has built-in Promise support as of version 1.18.0 (March 2014). You can return a promise from a test case, and Mocha will wait for it:
Don't forget the
return
keyword on the second line. If you accidentally omit it, Mocha will assume your test is synchronous, and it won't wait for the.then
function, so your test will always pass even when the assertion fails.If this gets too repetitive, you may want to use the chai-as-promised library, which gives you an
eventually
property to test promises more easily:Again, don't forget the
return
keyword!