Javascript 如何在测试中测试负面行为?就像调用API失败一样
当我的行为失败时,我试图测试我的行为。调用API的操作 我有这个:Javascript 如何在测试中测试负面行为?就像调用API失败一样,javascript,reactjs,ecmascript-6,redux,jestjs,Javascript,Reactjs,Ecmascript 6,Redux,Jestjs,当我的行为失败时,我试图测试我的行为。调用API的操作 我有这个: export const loadTips = (tips: TipsModel): LoadTips => ({ tips, type: LOAD_TIPS }); export const fetchTips: ActionCreator<ThunkType> = () => async (dispatch) => { return ApiService.getTips( tips
export const loadTips = (tips: TipsModel): LoadTips => ({ tips, type: LOAD_TIPS });
export const fetchTips: ActionCreator<ThunkType> = () => async (dispatch) => {
return ApiService.getTips(
tips => dispatch(loadTips(tips)),
() => dispatch(triggerToast('Tips are not loading. Try again later!', true))
);
};
因此,我想知道我可以做些什么来测试,例如,当操作失败时,它将调度操作:
dispatch(triggerToast('Tips are not loading. Try again later!', true))
那么我该如何测试该部分呢?因为这是一个负测试,所以你必须用负数据调用api。检查ApiService.getTips的实现并抛出错误。或模拟ApiService.getTips并抛出错误(调用错误回调)
由于这是一个否定的测试,你必须用否定的数据调用api。检查ApiService.getTips的实现并抛出错误。或模拟ApiService.getTips并抛出错误(调用错误回调)
在您的情况下,它将与积极测试相同:您需要模拟ApiService.getTips,这样它将称为“积极反馈”或“消极反馈”。比如说,现在您还没有测试在
getTips
成功时是否调度fetchTips
操作
它将是类似的(没有打字脚本):
在您的情况下,它将与积极测试相同:您需要模拟ApiService.getTips,这样它将称为“积极反馈”或“消极反馈”。比如说,现在您还没有测试在
getTips
成功时是否调度fetchTips
操作
它将是类似的(没有打字脚本):
dispatch(triggerToast('Tips are not loading. Try again later!', true))
ApiService.getTips(
tips => dispatch(loadTips(tips)),
() => dispatch(triggerToast('Tips are not loading. Try again later!', true))
)
it('dispatches loadTips on success', () => {
const mockedResponse = [1,2,3];
ApiService.getTips.mockImplementation(
(successCallback, failureCallback) => successCallback(mockedResponse)
);
store.dispatch(actions.fetchTips());
expect(store.getActions()).toContainEqual(actions.loadTips(mockedResponse));
expect(store.getActions()).not.toContainEqual(
triggerToast('Tips are not loading. Try again later!', true)
);
});
it('dispatches toast message on failure', () => {
ApiService.getTips.mockImplementation(
(successCallback, failureCallback) => failureCallback()
);
store.dispatch(actions.fetchTips());
expect(store.getActions()).toContainEqual(
triggerToast('Tips are not loading. Try again later!', true)
);
expect(store.getActions()).not.toContainEqual(actions.loadTips(mockedResponse));
});