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
Output - Test an onClick event using the React Testing Library - Clue Mediator
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.
App.js
import { useState } from 'react';
import './App.css';
function App() {
const [counter, setCounter] = useState(0);
return (
<div class="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 class="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
-
increment counter
Assert
- Counter should have a value of `1` after clicking the increment
-
decrement counter
Assert
- Counter should have a value of `-1` after clicking the decrement
App.test.js
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");
});
});
</app></app></app></app>
3. Output
Run the following command to test the cases.
npm test
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂