Jo *_*iss 12 javascript mocha.js chai es6-promise chai-as-promised
我正在使用Mocha来测试返回promise的异步函数.
测试承诺是否解析为正确值的最佳方法是什么?
从1.08.0版(2014年3月)开始,Mocha内置了Promise支持.您可以从测试用例中返回一个承诺,Mocha将等待它:
it('does something asynchronous', function() { // note: no `done` argument
return getSomePromise().then(function(value) {
expect(value).to.equal('foo');
});
});
Run Code Online (Sandbox Code Playgroud)
不要忘记return第二行的关键字.如果你不小心忽略它,Mocha会认为你的测试是同步的,它不会等待这个.then函数,所以即使断言失败你的测试也会一直通过.
如果这太重复了,你可能想要使用chai-as-promised库,它为你提供了一个eventually更容易测试promises 的属性:
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/);
});
Run Code Online (Sandbox Code Playgroud)
再次,不要忘记return关键字!
| 归档时间: |
|
| 查看次数: |
4233 次 |
| 最近记录: |