如何用Mocha测试承诺 [英] How to test promises with Mocha
问题描述
我正在使用Mocha来测试一个返回promise的异步函数。
I'm using Mocha to test an asynchronous function that returns a promise.
测试promise是否解析为正确值的最佳方法是什么?
What's the best way to test that the promise resolves to the correct value?
推荐答案
自1.18.0版(2014年3月)起,Mocha内置了Promise支持。您可以从测试用例中返回一个承诺,Mocha将等待它:
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:
it('does something asynchronous', function() { // note: no `done` argument
return getSomePromise().then(function(value) {
expect(value).to.equal('foo');
});
});
不要忘记 return
关键字第二行。如果你不小心忽略它,Mocha会假设你的测试是同步的,它不会等待 .then
函数,所以即使断言失败你的测试也会一直通过。
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.
如果这太重复了,你可能想要使用 chai-as-promised 库,它给你一个最终
属性来测试更多承诺容易:
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:
it('does something asynchronous', function() {
return expect(getSomePromise()).to.eventually.equal('foo');
});
it('fails asynchronously', function() {
return expect(getAnotherPromise()).to.be.rejectedWith(Error, /some message/);
});
再次,不要忘记返回
关键字!
Again, don't forget the return
keyword!
这篇关于如何用Mocha测试承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!