Getting started with Jest using TypeScript

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

Jest is a painless JavaScript unit testing framework from Facebook. It is designed to be super easy to setup and is packed full of powerful features. In this lesson we see how easy it is to add to your TypeScript project. This will be followed by a quick example application.

[00:00] To add Jest to a TypeScript project, we will simply npm install jest, the type definitions for Jest, and ts-jest, saving all of these to our devDependencies. Next, we will go ahead and copy the Jest config for TypeScript from the official Jest website to our package.json. Once we paste it in, we will go ahead and delete any extra braces.

[00:29] As all our application code for this project is in the source directory, we will also specify the roots that Jest should load test from as rootdir/src. To make it easier to run tests using Jest from the command line, we will go ahead and add an NPM test command that simply runs Jest from the project's node modules folder.

[00:54] Now, we are done with our Jest configuration. Let's write some code and test it. Currently, our project's main module under source index.ts is completely empty. We will go ahead and export a sum function. This function will take a variable number of arguments, each of type number.

[01:17] Then it will return the sum using Array.prototype.reduce, at each step returning the sum of the accumulator and the current value. We will go ahead and initialize the accumulator to zero. Now, let's write a unit test for this function using Jest.

[01:41] Jest automatically picks up any files in the tests directory. We will go ahead and create a test file for our main module. Within our test file, we will go ahead and, from the main module, bring in the sum function.

[02:03] Next, we will go ahead and create a basic test, passing in the function for our test body. Within our test, we will simply expect the sum of zero arguments to be zero. The test and the expect functions are coming from Jest, and thanks to the TypeScript definition, we get to use them with autocomplete, and compile time checking.

[02:31] We can run these tests from the terminal by simply running npm t, which runs the test target in our package.json. As you can see, our test passed with flying colors. You can even run the test in watch mode, using npm t, passing in an additional argument to Jest, watch o.

[02:53] Now, Jest goes ahead and runs all the tests. If we jump back to our spec file, duplicate the test, change the test name, add a test for adding two numbers with the expected result, you can see that Jest automatically picks up the new test, runs it, and it passed as expected.