我剛開始使用帶有 .spec.js 后綴的檔案來測驗 Jest 的檔案,所以希望這不是一個愚蠢的問題。我沒有通過 Google Stackoverflow 研究發現任何東西。
我想使用玩笑檢查包含新 window.location 的 if else 條件。
這是我的 file.ts
export const loadBSection = (bSectionId: string) => async (
dispatch: Dispatch,
getState: GetState,
{ bSectionApi }: Deps,
) => {
try {
...
} catch (e) {
dispatch(setBSectionErrorMessage(e.message));
if (e.response.status === 404) {
window.location.href = '/page-not-found.html';
}
}
};
我的 file.spec.ts
it('should .. and forward to a 404 page', async () => {
...
expect(store.getActions()).toEqual([setBSectionLoading(true), setBSectionErrorMessage(errorMessage)]);
// TODO what is expected here?
});
你有什么想法?
由于我是新手,也許您有一些深度潛水的資源?
我使用:https : //create-react-app.dev/docs/running-tests/作為介紹。您是否有其他有助于將來查找檔案的資源?
uj5u.com熱心網友回復:
我有一個想法,但不確定它是否有效
Object.defineProperty(window.location, 'href', {
writable: true,
value: '/page-not-found.html',
});
uj5u.com熱心網友回復:
解決了!
因此,設定responseoptional 以便其他錯誤也被捕獲是很有用的。此外,它更容易模擬功能,所以我改window.location.href到window.location.assign(url)。使相同但更易于測驗。
檔案.ts
catch (e) {
dispatch(setBSectionErrorMessage(e.message));
if (e.response?.status === 404) {
window.location.assign('/page-not-found.html');
}
}
檔案.spec.ts
我正在創建error和errorMessage內部測驗方法。在這里,您可以看到如何將錯誤物件與狀態代碼組合在一起作為回應:
it('should navigate to /page-not-found.html ...', async () => {
const bSectionIdMock = '123';
const error = Object.assign((new Error(), { response: { status: 404 } }));
bSectionApi.bSectionsBSectionIdGet.mockRejectedValue(error);
window.location.assign = jest.fn();
await store.dispatch(loadBSection(bSectionIdMock));
expect(window.location.assign).toHaveBeenCalledWith('/page-not-found.html');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324878.html
