DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

22

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

Billboard image

Monitoring as code

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay