我们可以用这种方式组成萨加斯
https://github.com/yelouafi/redux-saga/blob/5a6db57c77141b85b82aa097933ad687aacff8dc/docs/advanced/ComposingSagas.md
在下一个示例中,我将loadAssets
称为“ sub-saga” libraryChangeCategory
import * as LibraryActions from 'actions/libraryActions';
import loadAssets from './loadAssets';
export default function* libraryChangeCategory(category) {
yield put(LibraryActions.librarySetCategory(category));
yield put(LibraryActions.librarySetLoading());
yield* loadAssets();
yield put(LibraryActions.libraryResetLoading());
}
并测试两个第一良率即可。
import libraryChangeCategory from 'sagas/library/changeCategory';
const generator = libraryChangeCategory(LibraryCategories.Backgrounds);
let next;
it('should set category', () => {
next = generator.next();
expect(next.value).toEqual(
put(LibraryActions.librarySetCategory( LibraryCategories.Backgrounds )));
});
但是我不想在这里测试
loadAssets
生成器。我只想嘲笑它。
但是如何?看来这不可能吗?
function* mockGen() {
yield;
}
let loadAssets = libraryChangeCategory.__get__('loadAssets');
// don't work
loadAssets.__Rewire__(loadAssets.__get__('loadAssets'), mockGen);
// don't work too
spyOn(loadAssets, 'loadAssets').and.callFake(function(st) {
yield;
});
最佳答案
我找到了解决方案,而不是直接调用生成器,而是可以通过redux-saga.call
调用sub-saga,即您应该yield* loadAssets();
改成yield call(loadAssets);
而且比单元测试将仅仅是
import loadAssets from 'sagas/library/loadAssets';
it('should call sub-saga', () => {
next = generator.next();
expect(next.value).toEqual(call(loadAssets));
});