如何在 redux-saga 的开玩笑测试中产生多个值

How can I yield multiple values in a jest test of redux-saga

我刚刚开始使用 Jest 为我使用 redux-sagas 和生成器函数的 React Native 项目编写测试。我没有太多的测试经验,所以如果这是基本的东西,请原谅我的无知。

我有以下函数,它根据另一个函数的生成结果定义变量。我不知道如何模拟多个变量...

我的函数

export function * getAssets (api) {
  const bearerToken = yield select(selectBearerToken)
  const timelines = yield select(selectTimelines)

  if (timelines) {
    // Do stuff with timelines
    const response = yield call(api.getAssetById, bearerToken, 'abc123')
  }
}

我的测试

const stepper = (fn) => (mock) => fn.next(mock).value

test('getAssets', () => {
  const step = stepper(getAssets(FixtureAPI))
  const bearerToken = 'bearer_test_token'
  const timelines = 'mocked for brevity'

  expect(step()).toEqual(select(selectBearerToken))
  expect(step()).toEqual(select(selectTimelines))
  expect(step(timelines)).toEqual(call(FixtureAPI.getAssetById(bearerToken, 'B13fGCE_l')))
})

问题

调用getAssetById时,bearerToken未定义,但timelines已定义;因为我把它传给了step()。如何将 timelinesbearerToken 都传递给 step()?我会这样做吗?

您可以花一些时间在这里阅读有关 JavaScript 生成器的内容 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators,尤其是高级生成器部分。

长话短说,yield 将为 next 调用 yield 关键字后的表达式求值 return。在这种情况下,当您第一次调用 step() 时,return 值应该是 select(selectBearerToken) 的计算结果。 next 也可以接受一个值,即 .next(val),它将作为 yield 调用的 return 值传回。这就是当您第三次使用 timelines 调用 step() 时,它首先返回 timelines 到前一个 yield 调用,然后继续下一个 [=10] =] 并停止和 returns.

您要正确测试的方法是针对您的第二个 step() 调用,同时传回 bearerToken 的值,即 expect(step(bearerToken)).toEqual(select(selectTimelines))。然后,应该设置bearerToken。

一个建议是将 step() 调用与您的断言分开,以便更容易理解 IMO。