Test button when it is clicked - React testing library

Viewed 3044

I'm writing a test case for the Increment button when it is clicked.

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>
  );
}

Below is the test case that gives me error saying Matcher error: received value must be a mock or spy function How to expect the button is clicked when the click event is fired. Could anyone please help?

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

As jonrsharpe pointed out in his comment, the spirit of Testing Library is to test on the visible user interface rather than the implementation detail. So, instead of testing that the button was clicked, you actually want to test that the result of clicking the button is that the visible count increases by 1.

In other words, test for what the result of user actions should be, not that the user actions happened.

So for your incrementor, the following would be a good example assertion:

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