【问题标题】:Test button when it is clicked - React testing library单击时测试按钮 - React 测试库
【发布时间】:2021-04-30 02:35:10
【问题描述】:

我正在为单击增量按钮编写一个测试用例。

function App() {
  const [count, setCount] = useState(0);
  const handleIncrement = () => {
    if(count >= 0){
      setCount(count + 1);
    }
  }
  const handleDecrement = () => {
    if(count > 0){
      setCount(count - 1);
    }
  }
  return (
    <div>
      Count : {count}
    </div>
    <div>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
    </div>
  );
}

下面是给我错误的测试用例Matcher error: received value must be a mock or spy function 当点击事件被触发时,如何期望按钮被点击。有人可以帮忙吗?

  it('should handle count increment', ()=>{
    render(<App />);
    const incrementButton  = screen.getByRole('button',{name: 'Increment'})
    fireEvent.click(incrementButton)
    expect(incrementButton).toHaveBeenCalled()
  })

【问题讨论】:

  • 该测试没有意义 - 模拟点击不会调用按钮。按钮的 onClick 处理程序被调用,但这只是一个实现细节;测试相关状态更新的可见结果。

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

正如 jonrsharpe 在他的评论中指出的那样,测试库的精神是在可见的用户界面上进行测试,而不是在实现细节上进行测试。因此,您实际上想要测试的是单击按钮的结果是可见计数增加了 1,而不是测试按钮被单击。

换句话说,测试用户操作的结果应该是什么,而不是用户操作发生了。

因此,对于您的增量器,以下将是一个很好的示例断言:

expect(screen.queryByText('Count : 1')).toBeInTheDocument()

【讨论】:

  • 感谢您的解释。 queryByText 没用。我改用getByText
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2011-06-12
  • 2021-05-08
  • 2019-03-18
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多