javascript-茉莉花:如何期望承诺处理程序不会引发异常
作者:互联网
我有这个功能:
reload() {
myService.queryData()
.done(...)
.always(() => throw "fake exception"); //just to simulate the failure
}
我想要我的测试重载函数,并确保它不会引发异常,也不会在promise回调中引发异常.
describe("reload", function () {
it("does not throw exception", function (done) {
spyOn(myService, "queryData").and.callFake(() => {
let deffered = $.deffered();
setTimeOut(() => deffered.reject(), 0)
return deffered.promise();
});
reload();
setTimeout(() => {
//this is evaluated after the exception has been thrown, but
//how to check whether exception has been thrown
}, 2);
});
});
编辑:在某些情况下,如果已经定义了函数的返回类型,例如组件的生命周期事件,我可能无法返回诺言:
MyComponent extends React.Component {
componentDidMount() {
this.load(
galleryService.nodes().then(galleryResult => this.setState({ nodes: galleryResult.nodes }))
);
this.load(
galleryService.caches().then(cachesResult => this.setState({ caches: cachesResult.caches }))
);
}
}
var myComponent = React.createElement(MyComponent);
TestUtils.renderIntoDocument(myComponent); //this triggers the componentDidMount event and I need to make sure it won't throw error.
解决方法:
让reload返回它创建的承诺.在您的测试用例中,在其上附加一个catch处理程序,这会触发测试失败:
reload().catch(err => done.fail(err));
编辑问题后进行更新:如果无法更改原始函数的返回值,则将相关部分分解为单独的函数.例如:
function reloadNodes() {
return somePromise();
}
function reloadCaches() {
return anotherPromise();
}
function reload() {
reloadNodes();
reloadCaches();
}
然后,您可以测试reloadNodes和reloadCaches而不是重新加载.显然,您不需要为每个promise创建单独的函数,而是在适当的地方使用诸如Promise.all
之类的组合promise.
标签:jasmine,es6-promise,javascript 来源: https://codeday.me/bug/20191118/2028621.html