Testing click event in React Testing Library

Couple of issues with your approach.

First, creating an onClick mock like that won’t mock your button’s onClick callback. The callback is internal to the component and you don’t have access to it from the test. What you could do instead is test the result of triggering the onClick event, which in this case means verifying that <FiMinusCircle /> is rendered instead of <FiPlusCircle />.

Second, p is not a valid role – RTL tells you which roles are available in the DOM if it fails to find the one you searched for. The paragraph element doesn’t have an inherent accessibility role, so you’re better off accessing it by its content with getByText instead.

Here’s an updated version of the test:

test('clicking the button toggles an answer on/off', () => {
    render(<Question question="Is RTL great?" answer="Yes, it is." />);
    const button = screen.getByRole('button')
    
    fireEvent.click(button)
    // Here you'd want to test if `<FiMinusCircle />` is rendered.
    expect(/* something from FiMinusCircle */).toBeInTheDocument()
    expect(screen.getByText('Yes, it is.')).toBeInTheDocument()
    
    fireEvent.click(button)
    // Here you'd want to test if `<FiPlusCircle />` is rendered.
    expect(/* something from FiPlusCircle */).toBeInTheDocument();
    expect(screen.queryByText('Yes, it is.')).not.toBeInTheDocument()
})

Leave a Comment