如何对传奇的成分进行单元测试?

时间:2016-11-24 13:11:17

标签: javascript unit-testing mocking generator redux-saga

我们可以用这种方式组成传奇 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;
});

1 个答案:

答案 0 :(得分:4)

我找到了解决方案,而不是直接调用生成器,你可以通过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));
  });