Jest: A Unit Testing Framework

Learn how to install and set up Jest, followed by executing your inaugural test.

The story of testing frameworks and TypeScript

Over the years, there have been many unit testing frameworks that have been built for JavaScript. Some of the oldest, and therefore most mature, frameworks include Jasmine, QUnit and Mocha.

There have also been attempts to write unit testing frameworks in TypeScript, including MaxUnit or tsUnit, but these frameworks never really took off.

When using a unit testing framework, one of the most important things to consider is the range of testing features that it has:

  • Does it have the ability to raise errors, for example?

  • Can it mock out dependencies easily, such as an asynchronous call to a REST server or returning rows from a database?

  • Can it allow for special testing code to replace a function call completely?

  • Can it test throwing exceptions, and can it test rendered DOM elements?

The ease with which TypeScript can integrate with JavaScript libraries means we can use a fully featured JavaScript unit testing framework as if it were written in TypeScript.

Most testing frameworks have a similar suite of features, including a watch mode that will detect changes to test files and automatically re-run tests.

One of the popular testing frameworks currently available is Jest, which was written by the Facebook team and integrates with Babel, TypeScript, Node, React, Angular, and Vue.

Introduction to Jest

Jest is a simple-to-configure and powerful JavaScript unit testing framework that is built on top of the popular Jasmine framework.

Jasmine has been around for a very long time and is a mature, fully featured, and widely used testing framework. Jest enhances Jasmine by making it easier to configure, as well as providing a wealth of extra features.

Jest tests can also be run concurrently, which significantly speeds up the length of time a test suite will take to run. Jest is available through npm, and will therefore require an npm environment, which can be created as follows:

npm init

Here, we have initialized an npm project and can now install the required Jest packages as follows:

npm install jest --save-dev

With Jest installed, we can either run it using the command npx jest, or we can modify our package.json file to specify that Jest will be used when we run npm test.

Let’s update our package.json file as follows:

Get hands-on with 1200+ tech skills courses.