【问题标题】:Test React-Redux with mock context and actions使用模拟上下文和操作测试 React-Redux
【发布时间】:2017-06-27 08:02:48
【问题描述】:

如何测试 Reaect-Redux 组件并模拟其上下文和操作?

这样,它找不到任何动作:

    const wrapper = mount(
  <S437TransactionAuth
    store={store}
    s437updateGui="{mock.action.s437updateGUI}"
    setCurrentUserId="{mock.action.setCurrentUserId}"
  />,
        mockContext
    );

这找不到模拟动作或上下文

    const wrapper = mount(
        <Provider store={store}>
            <S437TransactionAuth
                s437updateGui="{mock.action.s437updateGUI}"
                setCurrentUserId="{mock.action.setCurrentUserId}"
            />
        </Provider>,
        mockContext
    );

标准做法是什么?我正在使用 Mocha,出于我无法控制的原因。

【问题讨论】:

    标签: reactjs mocha.js react-redux


    【解决方案1】:

    我们的标准做法是将连接组件导出为default,并将组件本身导出为命名导出。

    connect 已经为您测试过了,因此没有必要验证它实际上是在将内容从 Redux 存储传递到您的组件。您可以测试的是您的组件是否正确使用了该道具,您可以在未连接的组件中对其进行模拟。

    您还可以单独测试您在mapStateToPropsmapDispatchToProps 中分配的选择器和操作创建器。

    最后但并非最不重要的一点是,您始终可以简单地配置您的真实存储以进行测试(在您的describecalls 中!)并将您的主题包装在具有真实存储的 Provider 中。但这条路径可能会导致您必须调度一些操作来设置组件所期望的状态(例如模拟 API 调用以获取数据等)。

    【讨论】:

      【解决方案2】:

      假设您使用enzyme 进行挂载,上下文应该被传递为

      const wrapper = mount(
        <S437TransactionAuth
          // I'm assuming you have put your store in the context so I've removed store={store} for here
          s437updateGui="{mock.action.s437updateGUI}"
          setCurrentUserId="{mock.action.setCurrentUserId}"
        />,
              { context: mockContext }
          );
      

      我个人只是使​​用了 react-redux Provider,没有对 mount 的第二个参数做任何事情,就像这样

      const wrapper = mount(
              <Provider store={store}>
                  <S437TransactionAuth
                      s437updateGui="{mock.action.s437updateGUI}"
                      setCurrentUserId="{mock.action.setCurrentUserId}"
                  />
              </Provider>
          );
      

      另外,如果您还没有使用它,redux-mock-store 使测试 connected 组件变得更容易更多,但允许您设置要渲染的初始状态,在组件,或使用酶模拟用户对组件的操作,并针对模拟存储断言预期的操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多