我可以使用React Testing Library和Jest监视mapDispatchToProps函数而不丢失实现吗?

问题描述 投票:0回答:1

我们刚刚从酶迁移到React Testing Library。在此过渡中,我们发现几乎所有内容都更易于测试,但我们发现无法测试的情况。

每次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 Testing Library示例的codesandbox中显示了我的情况:

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

所以,当我有一个在mapDispatchToProps内部具有函数的连接组件时,如何监视它们?

谢谢!

我们刚刚从酶迁移到React Testing Library。在此过渡中,我们发现几乎所有内容都更易于测试,但我们发现无法测试的情况。每次API ...

reactjs redux react-redux jest react-testing-library
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.