"redux-saga-test-plan": "^4.0.1".
选项 1. 使用 withState:
对于静态,您可以只使用withState 方法让select 效果起作用。
选项 2。使用static provider
您可以通过静态提供程序以简洁的方式提供模拟值。将一组元组对(数组对)传入provide 方法。对于每一对,第一个元素应该是匹配效果的匹配器,第二个效果应该是您要提供的模拟值。
例如
saga.ts:
import { put, select } from 'redux-saga/effects';
const otherAction = { type: 'OTHER_ACTION' };
export const selector = (state) => {
console.log('selector');
return state.data;
};
export function* testedSagaFlow() {
const data = yield select(selector);
if (!data) {
return;
}
yield put(otherAction);
}
saga.test.ts:
import { expectSaga } from 'redux-saga-test-plan';
import { select } from 'redux-saga/effects';
import { selector, testedSagaFlow } from './saga';
describe('70199170', () => {
test('should dispatch other action', () => {
const state = { data: true };
return expectSaga(testedSagaFlow).withState(state).put({ type: 'OTHER_ACTION' }).run();
});
test('should return if data is nil', () => {
const state = { data: null };
return expectSaga(testedSagaFlow).withState(state).not.put({ type: 'OTHER_ACTION' }).run();
});
});
describe('70199170 - use provider', () => {
test('should dispatch other action', () => {
return expectSaga(testedSagaFlow)
.provide([[select(selector), true]])
.put({ type: 'OTHER_ACTION' })
.run();
});
test('should return if data is nil', () => {
return expectSaga(testedSagaFlow)
.provide([[select(selector), null]])
.not.put({ type: 'OTHER_ACTION' })
.run();
});
});
测试结果:
PASS redux-saga-examples packages/redux-saga-examples/src/stackoverflow/70199170/saga.test.ts
70199170
✓ should dispatch other action (30 ms)
✓ should return if data is nil (4 ms)
70199170 - use provider
✓ should dispatch other action (2 ms)
✓ should return if data is nil (3 ms)
console.log
selector
at selector (packages/redux-saga-examples/src/stackoverflow/70199170/saga.ts:6:11)
console.log
selector
at selector (packages/redux-saga-examples/src/stackoverflow/70199170/saga.ts:6:11)
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 2.934 s, estimated 3 s
Ran all test suites related to changed files.