DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Testing a button with jest

Testing a button with Jest:
I`m going to explain how to test a simple button with jest in a react component.

We are going to start by coding the button:

Image description

The one above is gonna be out button where we are passing all the props from the last button to it, and also a title.

Image description

This is going to return as we run one test.
Now I`m going to take the code apart and explain it.

The first 3 lines i`m basically just importing the things i will need.

Then in order to start the test, we put test and then inside what we are about to test and afterwards an anonymous function to start the actual test.
We being with onClick = jest.fn() which is basically to represent the function.
Then we render the element with the function and a title.
After that we will take the button created to take it by getting the text we assigned to it before hand.
We are going to use the fireEvent.click(buttonElement) to mock the clicked by someone.
And finally we are going to put an expect(), and we expect to the button to be clicked 1 one time.

Hope someone found it useFul.

Lautaro

Top comments (0)