测试 redux-saga takeEvery

Testing redux-saga takeEvery

我有以下超级简单的 Redux-Saga,我想用 Jest 进行测试。

function* nextApi() {
  yield* takeEvery(
    (action) => !!(action.meta && action.meta.next),
    nextApiSaga
  )
}

我看过 Redux-Sagas-Test-Plan, but that only seems to allow you to unit test functions that contain Saga Effect Creators and doesn't seem to support Saga Helpers. There is also Redux-Saga-Test 但它只是对产生的效果做了 deepEqual,并没有测试箭头函数。

我想要做的是将以下两个对象传递给 takeEvery 并查看 nextApiSaga 仅在第二种情况下被调用。

{ type: 'foo' }

{ type: 'foo', meta: { next: 'bar' } }  

采用不同的方法,我想到了这个。不确定这是否是最佳答案,但它似乎有效。如果其他人遇到同样的问题并且仍然愿意接受更好的建议,请在此处添加。

function getTakeEveryFunction(saga) {
  return saga().next().value.TAKE.pattern
}

it('takes actions with meta.next property', () => {
  const func = getTakeEveryFunction(nextApi)
  expect(func({ type:'foo' })).toBe(false)
  expect(func({ type:'foo',  meta: { next: 'bar' } })).toBe(true)
})

我给你留下了关于 redux-saga-test-plan 具有 saga 助手方法的评论,但你可以使用它轻松测试 takeEvery。使用您的传奇调用 testSaga,然后使用模式调用 takeEvery 方法断言(注意我保留对您的原始匿名函数的引用)和其他传奇。

const helper = action => !!(action.meta && action.meta.next)

function* nextApi() {
  yield* takeEvery(
    helper,
    nextApiSaga
  )
}

testSaga(nextApi).takeEvery(helper, nextApiSaga)