[英]Jasmine: How to expect promise handler to not throw exception
我有這個功能:
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);
});
});
編輯:我可能無法在某些情況下返回一個promise,其中函數的返回類型已經定義,例如組件的生命周期事件:
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
而不是reload
。 顯然,您不需要為每個承諾創建單獨的函數,而是在適當的情況下使用Promise.all
東西來組合您的承諾。
我相信窺探window.onerror
是要走的路:
describe("reload", function () {
it("does not throw an exception", function (done) {
spyOn(window, 'onerror').and.callFake((error: any, e: any) => {
fail(error);
});
spyOn(myService, "queryData").and.callFake(() => {
let deffered = $.deffered();
setTimeout(deffered.reject, 0);
return deffered.promise();
});
});
setTimeout(done, 2);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.