我有这样的功能:茉莉:如何指望承诺处理程序没有抛出异常
reload() {
myService.queryData()
.done(...)
.always(() => throw "fake exception"); //just to simulate the failure
}
我想我的测试重装功能,并确保它不会抛出异常,也不承诺回调做。
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.
不能使用'Promise.all'或'Promise.race'协调在您的编辑片段流? – MarcoL
我可以,但componentDidMount由框架(REACT)定义为返回void的函数,我不直接调用它。当我执行'TestUtils.renderIntoDocument(...)'时,它被框架调用。我希望我可以孤立问题香草javascript,但我没有正确阐明问题... – Liero
我仍然不明白为什么你不能返回一个'Promise.all'包含'componentDidMount所有的承诺'或者将相关的代码分解成一个单独的,可测试的函数,你可以从'componentDidMount'调用。 –