The fireEvent utility in React Testing Library supports all the events that you regularly use in the web (change, click, etc.). Let’s see how we can test our change event handler with an input.
Component:
<input id="favorite-number" type="number" value={number} onChange={handleChange} /> {isValid ? null : <div role="alert">The number is invalid</div>}
As we can see, the input has a 'onChange' event, and also there is a message display when the number is outside [1, 9]
Test:
import React from 'react' // extend expect object to have methods from jest-dom import '@testing-library/jest-dom/extend-expect' import { render, fireEvent } from '@testing-library/react' import { FavoriteNumber } from './favorite-number' test('entering an invalid value shows an error message', () => { const { getByLabelText, getByRole } = render(<FavoriteNumber />) const input = getByLabelText(/favorite number/i) // fire a change event fireEvent.change(input, { target: { value: 10 } }) expect(getByRole('alert')).toHaveTextContent(/the number is invalid/i) })