Jest Testing
Let's get started with Jest in this lesson.
We'll cover the following
Benefits of using Jest
Several testing libraries and frameworks are available for JavaScript. Among them, Jest has several decisive advantages when working with React:
-
Like React, it was created by Facebook, and the two work very well together.
-
Jest has useful functions for evaluating component renderings.
-
Jest runs the tests quickly.
-
It’s easy to run tests automatically in continuous integration workflows or as a watcher re-evaluating your code after every change.
-
It comes pre-loaded when you start your application with
create-react-app
, as we did. -
Jest is easy to use. We only need to place test functions into correctly named test files and then run the test script. No special configuration is required.
Naming conventions for testing files
A few options exist for naming your test files. A popular choice is to infix a .test
so that myfile.js
has an accompanying file called myfile.test.js
that contains the tests. Returning to our React example, we modify the test file App.test.js
, which has already been created by create-react-app
, corresponding to the React file App.js
. It can be found in the same directory as App.js
. If you prefer, you can name it with a jsx
suffix. Jest will find it either way.
To start, we’ll make App.test.js
an empty test file and then run the test watcher using the npm test
. When there are no tests in a test file, the test suite fails. The output should show that we’re failing one test.
Try it yourself
The tests will fail in the widget below because our .test.js
file is empty.
Get hands-on with 1200+ tech skills courses.