Test an onClick event using the React Testing Library
Today we will show you how to test an onClick event using the React Testing Library. Here, we will use the fireEvent.click()
to handle the button click event.
In the previous articles, we learned how to write test cases for react application using React Testing Library.
We have also checked a checkbox using the testing library and handle a checkbox event.
Output: Unit Testing
Test an onClick event using the React Testing Library
1. Create a counter app
Let’s create a simple counter application using the create-react-app and increment/decrement the counter using button click.
Look at the following component for the counter app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { useState } from 'react'; import './App.css'; function App() { const [counter, setCounter] = useState(0); return ( <div className="App"> <h1>Counter Application</h1> <small>Powered By <a href="https://www.cluemediator.com/" target="_blank" title="Clue Mediator" data-testid="powered-by" rel="noopener noreferrer">Clue Mediator</a></small> <h2 className="counter" data-testid="counter-text" >{counter}</h2> <button onClick={() => setCounter(prevCounter => prevCounter + 1)} data-testid="btn-increment"> Increment </button> <button onClick={() => setCounter(prevCounter => prevCounter - 1)} data-testid="btn-decrement"> Decrement </button> </div> ); } export default App; |
2. Write a test cases
Let’s test the following test cases for the counter application. Here, we will mostly focus on the button click event. You may also check this article for other test cases.
display counter text
Assert
- Counter text should have
0
value
- Counter text should have
increment counter
Assert
- Counter should have a value of
1
after clicking the increment
- Counter should have a value of
decrement counter
Assert
- Counter should have a value of
-1
after clicking the decrement
- Counter should have a value of
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import { render, screen, fireEvent } from '@testing-library/react'; import App from './App'; describe("<App />", () => { test('display counter text', () => { render(<App />); expect(screen.getByTestId("counter-text")).toHaveTextContent("0"); }); test('increment counter', () => { render(<App />); const btnIncrement = screen.getByTestId("btn-increment"); fireEvent.click(btnIncrement); expect(screen.getByTestId("counter-text")).toHaveTextContent("1"); }); test('decrement counter', () => { render(<App />); const btnDecrement = screen.getByTestId("btn-decrement"); fireEvent.click(btnDecrement); expect(screen.getByTestId("counter-text")).toHaveTextContent("-1"); }); }); |
3. Output
Run the following command to test the cases.
1 | npm test |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂