过去,我们使用Redux Thunk,它更易于测试。将其转换为Redux-Saga后,看起来像这样:
import { takeLatest, put } from "redux-saga/effects";
function* fetchTasksSaga(){
try {
const taskResponse = yield fetch("API URL")
const tasks = yield taskResponse.json()
yield put(fetchTasksSuccess(tasks));
} catch (error) {
yield put(fetchTasksError(error.message));
}
}
export default function* watchFetchTasksSaga(){
yield takeLatest("FETCH_TASKS_START", fetchTasksSaga)
}
对于此摘要,它看起来像是一个开玩笑的测试吗?
它看起来类似于下面的代码:
describe('saga testing watchFetchTasksSaga', () => {
it('should test watchFetchTasksSaga', () => {
const gen = watchFetchTasksSaga();
expect(gen.next().value).toEqual(takeLatest("FETCH_TASKS_START", fetchTasksSaga));
});
});
describe('test fetchTasksSaga', () => {
const gen = cloneableGenerator(fetchTasksSaga)();
expect(gen.next().value).toEqual(fetch("API URL"));
it('test fetchTasksSaga success scenario', () => {
const gen1 = gen.clone();
const data = '2cd09fe0-3b6f-11ea-b05a-3b06a24be1d6';
const response = { data };
expect(gen1.next(response).value).toEqual(response.json());
expect(gen1.next().value).toEqual(
put(fetchTasksSuccess(tasks)),
);
expect(gen1.next().done).toBe(true);
});
it('should test error scenario', () => {
const gen1 = gen.clone();
const error = {
message: 'some error',
};
expect(gen1.throw(error).value).toEqual(
put(fetchTasksError(error.message)),
);
});
});