在我的传奇中,我调用了一个api请求。
function* sendRequestSaga(): SagaIterator {
yield takeEvery(Actions.sendRequest.type, sendApiRequest);
}
function* sendApiRequest(action: Action<string>) {
try {
yield call(/*args for calling api*/);
} catch (error) {
// Handle error
}
}我已经为成功案例创建了单元测试。现在,我想为调用api返回异常的情况创建一个单元测试。
it("Should handle exception correctly", () => {
const expectedException = new Error("my expecting exception");
return expectSaga(mySaga)
.provide([
[call(/*args for calling api*/), expectedException],
])
.call(/*args for calling api*/)
.dispatch({
type: Actions.sendRequest.type,
payload: /*args*/
})
.silentRun()
.then(() => {
// My assertion
});
}但这并不起作用,因为provide只为call方法返回一个值,而不是抛出new Error对象。因此,错误对象不会被捕获。如何模拟抛出错误操作?
发布于 2019-10-15 16:12:00
事实证明,它可以通过redux-saga-test-plan中的throwError()实现
import { throwError } from "redux-saga-test-plan/providers";
it("Should handle exception correctly", () => {
const expectedException = new Error("my expecting exception");
return expectSaga(mySaga)
.provide([
[call(/*args for calling api*/), throwError(expectedException)],
])
.call(/*args for calling api*/)
.dispatch({
type: Actions.sendRequest.type,
payload: /*args*/
})
.silentRun()
.then(() => {
// My assertion
});
}https://stackoverflow.com/questions/58386912
复制相似问题