请原谅标题。我是Sagas的新手,他写了一个基本的Saga,当单击按钮时,它会从API中获取内容,然后执行更多操作。但是,我一直无法测试任何东西。
我的传奇:
export function* fetchWorker() {
yield put({ type: 'BEGIN_LOADING' }); // This is a test put that was added to help diagnose the problem
try {
const response = yield call(
axios.get,
'http://localhost:<port>/<path>',
);
yield put(fetchSucceeded(response.data));
} catch (error) {
yield put(fetchFailed(error));
}
}
export function* fetchWatcher() {
yield takeEvery(types.FETCH_REQUESTED, fetchWorker);
}
export default function* rootSaga() {
yield all([fetchWatcher()]);
}
我的测试:
describe('Test Saga', () => {
it('Fetches successfully', () => {
const gen = fetchWorker();
expect(gen.next().value).toEqual(put({ type: 'BEGIN_LOADING' }));
expect(gen.next().value).toEqual(
call(axios.get, 'http://localhost:<port>/<path>'),
);
expect(gen.next().value).toEqual(put(fetchSucceeded(undefined)));
expect(gen.next('test').value).toEqual(
put({ type: types.FETCH_SUCCEEDED, data: 'test' }),
);
expect(gen.next()).toEqual({ done: true, value: undefined });
});
但是,我从来没有超越第一个期望。取而代之的是,我得到了它(稍作重新排列以使其更具可读性:
expect(received).toEqual(expected) // deep equality
- Expected
+ Received
Object {
"@@redux-saga/IO": true,
- "combinator": false,
- "payload": Object {
- "args": Array [
- "http://localhost:<port>/<somepath>",
],
- "context": null,
- "fn": [Function wrap],
- },
- "type": "CALL",
+ "combinator": true,
+ "payload": Array [
+ GeneratorFunctionPrototype {
+ "_invoke": [Function invoke],
+ },
+ "type": "ALL",
}
我认为可能是因为我使用all()
的方式,所以我用观察者的传奇故事和takeEvery()
或takeLatest()
替换了根传奇,但它们都返回相同的错误,文字略有不同。这些物体从哪里来?为什么它们与我的期望有如此大的差异?
我正在遵循官方文档here以及其他地方(尤其是this guide)上的说明。
我也在其他地方看过,并且看到了许多与我自己的例子相似的例子。怎么了?
答案 0 :(得分:0)
最好编写3个Saga测试用例,每个功能一个。
1. rootSaga:
const gen = rootSaga();
expect(gen.next().value).toEqual(all([fetchWatcher()]));
expect(gen.next().done).toBe(true)
2. fetchWatcher:
const gen = fetchWatcher();
expect(gen.next().value).toEqual(takeEvery(types.FETCH_REQUESTED, fetchWorker));
expect(gen.next().done).toBe(true)
3. fetchWorker:
const gen = fetchWorker();
expect(gen.next().value).toEqual(put({ type: 'BEGIN_LOADING' }));
expect(gen.next().value).toEqual(
call(axios.get, 'http://localhost:<port>/<path>'),
);
const response = { data: 'dummy data' };
expect(gen.next(response).value).toEqual(put(fetchSucceeded(response.data)));
expect(gen.next().done).toBe(true);