我有這樣的功能:茉莉:如何指望承諾處理程序沒有拋出異常
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'調用。 –