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.
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.
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.
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.
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.
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.
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.
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.