DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

23

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay