This video is available to students only

Jest & React Testing Library

In this lesson, we'll talk about the two main testing tools we'll use to test our React components - Jest & React Testing Library.

We'll be using two primary testing tools to test our React components.

Jest#

Jest is a framework for writing JavaScript tests. It allows us to specify our test suites with describe and it blocks. We use the describe function to segment each logical unit of tests and inside that we can use the it function for each expectation we'd want to assert.

Jest also comes with a large suite of expect assertions. These assertions gives us access to a number of "matchers" that let us validate different things. For example:

Be sure to check out Jest's expect assertions documentation to see a list of all the different assertions that can be made.

Among other things, Jest also comes with a lot more functionality such as mocking support and snapshot testing. A huge advantage to using Jest is all of this functionality often comes with minimal to no configuration/set-up.

React Testing Library#

React Testing Library is a lightweight library, that works with any testing framework to provide a set of helper methods to help test React components. A key aspect to this library is that it provides methods to test components without focusing on implementation details.

We'll go through an example testing scenario to illustrate how the React Testing Library can be used. Assume we had a simple component that displayed a counter that when clicked - simply increments the value of a number in the page. This example comes from the example shown in the React docs for Using the State Hook.

If we wanted to write unit tests for this component, there are two underlying test cases that we can think about conducting.

  • Component displays a count of 0 when initialized.

  • When a user clicks the button, the number displayed in the UI is incremented by one.

Start a new discussion. All notification go to the author.