export function* testGeneratorFunction() {
try {
yield put(showSuccess(success));
} catch (error) {
yield put(showError(error));
}
}
在上面的函数中,我需要测试catch块。我必须测试是否调用了showError()函数。
答案 0 :(得分:2)
您可能希望使用帮助程序库,例如redux-saga-testing。
免责声明:我写了这个库来解决同样的问题
对于您的具体示例,使用Jest(但对Mocha也一样),您可以写:
import sagaHelper from 'redux-saga-testing';
import { call, put } from 'redux-saga/effects';
import { showSuccess, showError } from './my-actions';
import { api } from './my-api';
function* testGeneratorFunction() {
try {
const data = yield call(api);
yield put(showSuccess(data));
} catch (e) {
yield put(showError(e.message));
}
}
describe('When testing a Saga that throws an error', () => {
const it = sagaHelper(testGeneratorFunction());
it('should have called the API first, which will throw an exception', result => {
expect(result).toEqual(call(api));
return new Error('Something went wrong');
});
it('and then trigger an error action with the error message', result => {
expect(result).toEqual(put(showError('Something went wrong')));
});
});
describe('When testing a Saga and it works fine', () => {
const it = sagaHelper(testGeneratorFunction());
it('should have called the API first, which will return some data', result => {
expect(result).toEqual(call(api));
return 'some data';
});
it('and then call the success action with the data returned by the API', result => {
expect(result).toEqual(put(showSuccess('some data')));
});
});
我稍微修改了你的例子,因为" put"永远不会抛出异常。
在现实生活中,对API或其他逻辑的调用更有可能引发异常。
上找到许多其他示例(更复杂的示例)答案 1 :(得分:2)
手册中Error Handling有一个不错的章节。简而言之,您可以使用.throw
代替.next
来触发您的传奇中的catch
阻止:
assert.deepEqual(
gen.throw({message: "error!").value, // <-- notice the throw instead of next
put({ type: 'PRODUCTS_REQUEST_FAILED', error }),
"fetchProducts should yield an Effect put({ type: 'PRODUCTS_REQUEST_FAILED', error })"
)
我不熟悉Chai语法,但是例如使用Jest的expect
它将是:
expect(gen.throw({message: "server ded"}).value).toEqual(
put({ type: 'PRODUCTS_REQUEST_FAILED', error })
)