首页 > 解决方案 > 我可以在不丢失实现的情况下使用 React 测试库和 Jest 监视 mapDispatchToProps 函数吗?

问题描述

我们刚刚从 Enzyme 迁移到 React 测试库。在这个过渡中,我们发现几乎所有东西都更容易测试,但我们发现了一个我们无法测试的案例。

每次 API 请求失败时,我们都会通过调用操作向用户展示祝酒词。由于 DOM 的那部分没有被渲染,我们无法在屏幕中搜索 toast,但我们可以测试至少该操作正在被调用。

但是,无论我如何尝试监视该功能,我都无法正确监视。

基本上,我的案例是一个连接组件,并且想要监视一个动作,如下所示:

// These actions are normally in a different file, but there is no difference
const increment = () => ({type: 'INCREMENT'})
const decrement = () => ({type: 'DECREMENT'})

// My component
const Counter = ({increment, decrement, count}) => {
  return (
    <div>
      <h2>Counter</h2>
      <div>
        <button onClick={decrement}>-</button>
        <span data-testid="count-value">{count}</span>
        <button onClick={increment}>+</button>
      </div>
    </div>
  )
}

const mapStateToProps = state => ({count: state.count})
const mapDispatchToProps = {
  increment,
  decrement,
}

// The connected component that I'm testing
const ConnectedCounter = connect(mapStateToProps, mapDispatchToProps)(Counter)

这将是失败的测试:

// render is the helper function that renders with the store. See implementation on codesandbox below.
test('can spy on action that was dispatched', () => {
  const mockIncrement = jest.fn().mockImplementation(increment)
  render(<ConnectedCounter increment={mockIncrement} />)
  fireEvent.click(screen.getByText('+'))
  expect(mockIncrement).toHaveBeenCalledTimes(1)
})

我宁愿不要因为商店内的增强器中处理操作的方式而失去真正的实现。

我已经完成了修改并添加了一个失败的测试,该测试在所有 React 测试库示例的代码框中显示了我的案例:

https://codesandbox.io/s/romantic-ishizaka-spkk1?file=/src/tests/react-redux.js _ _

那么,当我在 mapDispatchToProps 中有一个带有函数的连接组件时,我该如何监视它们呢?

谢谢!

标签: reactjsreduxreact-reduxjestjsreact-testing-library

解决方案


我不是 RTL 专家,但我认为这里的建议是更改您要测试的内容。

从概念上讲,您不应该尝试验证组件是否专门调用了props.increment. 相反,您应该检查组件中的文本内容是否在单击后从“0”变为“1”。重点应该放在它是否产生了正确的结果,而不是如何实现该行为。


推荐阅读