【问题标题】:Testing Redux Saga, using values from the action that triggers it使用触发它的操作中的值测试 Redux Saga
【发布时间】:2017-01-16 11:51:14
【问题描述】:

我有一个运行良好的 saga,我调用一个动作并包含一些数据,这个 saga 被触发,它从动作中提取值,执行一个 API 调用并以几个 yield put 结束 - 太棒了。

我现在正在尝试测试该传奇并遇到问题,我已经编写了一个简单的传奇并进行测试以尝试缩小问题所在。

传奇:

function* exampleSaga() {
  while(true) {
    yield take('EXAMPLE_SAGA');
    console.log('what is the value inside example');
    const { value } = yield take('ANOTHER_ACTION')
    console.log('value', value);
    yield take('THIRD_TAKE')
  }
}

export { exampleSaga }

测试:

describe('Saga::Example ', function() {
  it('should take EXAMPLE_SAGA ', () => {
    const saga = exampleSaga()

    expect(saga.next().value).to.deep.equal(take('EXAMPLE_SAGA'))
    expect(saga.next({
      type: 'ANOTHER_ACTION',
      value: 'amazing'
    }).value).to.deep.equal(take('ANOTHER_ACTION'))
    expect(saga.next().value).to.deep.equal(take('THIRD_TAKE'))
  })
})

我期望的是,因为我正在调用 next() 并传递一个对象(一个模拟的 redux 操作),所以我应该能够从 saga 中的该操作中提取值。

我得到的是:

TypeError: Cannot read property 'value' of undefined

令人沮丧的一件事是,在我的应用程序中,使用这种语法从操作中获取值的 saga 是有效的:

const { value1, value2 } = yield take('ACTION_NAME')

只有在我尝试测试 saga 时才会出现问题。

感谢任何帮助。

【问题讨论】:

    标签: reactjs redux react-redux redux-saga


    【解决方案1】:

    它按预期工作。在您的代码中,您断言 saga 正在等待一个动作(而不是推动它)。因此,您必须将值对象传递给下一次迭代:

    // expecting that saga waits for EXAMPLE_SAGA action
    expect(saga.next().value).to.deep.equal(take('EXAMPLE_SAGA'))
    
    // pushing EXAMPLE_SAGA action and expecting that saga waits for ANOTHER_ACTION
    expect(saga.next().value).to.deep.equal(take('ANOTHER_ACTION'))
    
    // pushing ANOTHER_ACTION and expecting that saga waits for THIRD_TAKE action
    expect(saga.next({
      type: 'ANOTHER_ACTION',
      value: 'amazing'
    }).value).to.deep.equal(take('THIRD_TAKE'))
    

    【讨论】:

    • 感谢您的回答,我刚刚在本地更新了我的示例代码,现在得到了我所期望的。我现在对如何测试生成器有了更好的理解:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    相关资源
    最近更新 更多