JavaScript: Testing Your Code With Jest.js

Martin Crabtree
4 min readApr 9, 2020

--

What is Jest.js?

Jest.js is a JavaScript testing framework that can be used to generate automated tests and coverage reports for your code. It is a common framework that is used in real-world development so I thought it would be helpful to provide an introduction to using Jest.js in a development environment.

Installing Jest.js

To install Jest.jst, use the Bash Command Line to navigate to your program folder and use npm to create a new JavaScript project with the command “npm init -y”.

To install, use the bash command line to navigate to your program folder and install jest by typing, “npm install jest — save-dev”. Since you will only deploy tested code, the “ — save-dev” tag only installs Jest to your development environment for testing.

We also need to add Jest to the package.json file so that npm is aware of Jest when running and testing code.

Writing a Simple Test

First create a new folder in your project called “_tests_” to house all of the tests that will be referenced by Jest.

Inside we will create a test file in the format “xxxxx.spec.js”, where xxxxx should be a descriptive reference to the function of the test.

Jest comes with a series of global methods that are accessible without an import or require reference. A full list of methods can be found here. In this case we will use the describe() method, which accepts two arguments: a name (String), and a function.

In this case the function we want to execute is the Jest.js global test() function, which accepts the following arguments: a test name (String), function, and an optional timeout duration (in milliseconds). In this example we create a test case called “Cat Checker”, with a test that checks to see if the animal property of an object contains the word “CAT”.

This test has 3 components: an input, an output, and the Jest.js expect() function. The expect() function usually houses a matcher function that evaluates if the given input returns the expected output. In this we compare the result of a custom filterByTerm function to the expected output using the toEqual() matcher function.

Code Coverage:

Code coverage is a measure of how much code has been checked by the testing software. Conveniently, Jest.js has a built in code coverage reporting utility tied to its testing function. To run a code coverage report, add the “ — coverage” flag when running a test from the command line.

Jest.js also has an option to visualize your code coverage report in HTML format. To enable this feature add the following properties to your package.json file.

This now, after running your tests, the results can be viewed by opening the newly created ../coverage/index.html file.

For more info on the other tests available in Jest.js, check out their documentation at https://jestjs.io/en/. Happy testing!

Sources:

https://www.valentinog.com/blog/jest/

--

--