There are several different ways of React component testing, but I chose for this particular combination because create-react-app uses Jest as their default test runner.

Furthermore I used @testing-library/react for providing utilities to test React components and @testing-library/jest-dom for useful DOM assertion functions.

First off I created a simple custom datepicker element I wanted to use for testing. It contains 2 select fields for the day and month, and a number input for the year.

In the simple example below I test a few simple use cases. Do the inputs have the right values when I provide no default selected date? What if I do provide a default selected date? What if a user selects a value? Just a few simple examples to show you how to use the combination of libraries mentioned above.

A few useful know-hows worth mentioning:

  • The getByTestId() function looks for elements within your component with the data-testid attribute
  • Use fireEvent for firing DOM events. Take a look at the documentation to find out what events can be mocked, there are a lot of them!
  • @testing-library/react even provides a hydrate testing method. Useful for testing how your components are rendered after SSR.

Cheers!