Firing events in tests
React Testing Library provides a fireEvent
method that can be used to fire Document Object Model (DOM) events in your test cases. In the following example, we will create a test case that opens our car addition modal form.
First, add the following imports to the App.test.js
file:
import { render, screen, fireEvent } from '@testing-library/react'; import App from './App';
Next, we will create a new test case in the App.test.js
file, as follows:
test('open add car modal form', () => { });
Then, we use fireEvent.click
, which creates a click event to a given DOM element. In our case, the DOM element is the button to open the modal form, and we can find it by using a getByText
query, like this:
test('open add car modal form', async () => { render(<App />); fireEvent.click(screen.getByText('New Car')); });
Finally, we verify that the modal dialog form is opened...