关注官方文档:Branching Saga.
有时你的传奇会有不同的结果。要在不重复导致它的所有步骤的情况下测试不同的分支,您可以使用实用函数 cloneableGenerator
例如(测试策略:逐步测试生成器。)
saga.ts:
import { call, put } from 'redux-saga/effects';
export function constructApiData(params) {
return { name: 'teresa teng' };
}
export function postData(url, formData) {
return fetch(url, { body: formData });
}
export function saveRecommendations(payload) {
return { type: 'SAVE_RECOMMENDATIONS_SUCCESS', payload };
}
export function* saga(onFormSubmitSuccess) {
const modifyData = {};
const url = 'https://test.com';
const formData = yield call(constructApiData, modifyData);
const response = yield call(postData, url, formData);
if (response.data.attributes.status === 'SUCCESS') {
yield put(saveRecommendations(response.data.attributes.recommendedPriorities));
yield call(onFormSubmitSuccess);
}
}
saga.test.ts:
import { constructApiData, postData, saga, saveRecommendations } from './saga';
import { cloneableGenerator } from '@redux-saga/testing-utils';
import { call, put } from 'redux-saga/effects';
describe('64419302', () => {
function mockOnFormSubmitSuccess() {}
const gen = cloneableGenerator(saga)(mockOnFormSubmitSuccess);
it('should construct api data', () => {
expect(gen.next().value).toEqual(call(constructApiData, {}));
});
it('should call api', () => {
expect(gen.next(constructApiData({})).value).toEqual(call(postData, 'https://test.com', { name: 'teresa teng' }));
});
describe('success', () => {
let clone;
beforeAll(() => {
clone = gen.clone();
});
it('should save data', () => {
expect(
clone.next({ data: { attributes: { status: 'SUCCESS', recommendedPriorities: [1, 2, 3] } } }).value,
).toEqual(put(saveRecommendations([1, 2, 3])));
});
it('should call form submit success callback', () => {
expect(clone.next().value).toEqual(call(mockOnFormSubmitSuccess));
});
});
});
测试结果:
PASS src/stackoverflow/64419302/saga.test.ts
64419302
✓ should construct api data (4 ms)
✓ should call api
success
✓ should save data (1 ms)
✓ should call form submit success callback
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 94.12 | 50 | 75 | 93.33 |
saga.ts | 94.12 | 50 | 75 | 93.33 | 7
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 2.923 s, estimated 3 s