我正在测试一个民调传奇。
export function* sagaWithPolling() {
while (true) {
try {
// saga body
} catch (error) {
yield put(stopPolling());
yield put(displayError(error));
}
}
}测试:
describe('error flow', () => {
const saga = sagaWithPolling();
saga.next();
test('stop polling', () => {
const actual = saga.throw(TEST_ERROR).value;
const expected = put(stopPolling());
expect(actual).toEqual(expected);
});
test('should display error', () => {
const actual = saga.next().value;
const expected = put(displayError(TEST_ERROR));
expect(actual).toEqual(expected);
});
test('be done', () => {
const actual = saga.next().done;
const expected = true;
expect(actual).toEqual(expected);
});
});这个测试对于一般的传奇来说是通过的,但是对于轮询和使用while(true)的测试,它在最后一步失败了,因为saga.next().done是false,因为它继续轮询。你知道如何指出它停止了轮询吗?
发布于 2021-06-22 15:16:52
由于在生成器中定义了无限循环,gen.next()将让生成器在该无限循环(try块)中无限取值。该值始终为{value: 1, done: false}。生成器将永远不会结束。
您应该使用Generator.prototype.return()返回给定值并完成生成器。
例如。
saga.ts
import { put } from 'redux-saga/effects';
export function stopPolling() {
return { type: 'STOP_POLLING' };
}
export function displayError(error) {
return { type: 'DISPLAY_ERROR', payload: error };
}
export function* sagaWithPolling() {
while (true) {
try {
// saga body
yield 1;
} catch (error) {
yield put(stopPolling());
yield put(displayError(error));
}
}
}saga.test.ts
import { put } from 'redux-saga/effects';
import { displayError, sagaWithPolling, stopPolling } from '.';
describe('error flow', () => {
const saga = sagaWithPolling();
const TEST_ERROR = new Error('network');
saga.next();
test('stop polling', () => {
const actual = saga.throw(TEST_ERROR).value;
const expected = put(stopPolling());
expect(actual).toEqual(expected);
});
test('should display error', () => {
const actual = saga.next().value;
const expected = put(displayError(TEST_ERROR));
expect(actual).toEqual(expected);
});
test('be done', () => {
const actual = saga.return().done;
const expected = true;
expect(actual).toEqual(expected);
});
});测试结果:
PASS src/stackoverflow/65237271/index.test.ts
error flow
✓ stop polling (3 ms)
✓ should display error (1 ms)
✓ be done
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 2.067 s, estimated 3 shttps://stackoverflow.com/questions/65237271
复制相似问题