July 30, 2020
If, like me, you have fallen in love with typescript you’ll undoubtedly be using it for every project where it has an applicable use. However if you’re also like me in that your main exposure to typescript and testing has come through Angular and its Jasmine testing through Karma, you won’t really know how to set up your project for testing if it is not an angular project. I recently created such a project and in this post I’ll talk you through my process of setting up and testing it with a Jest using ts-jest. If you’re unfamiliar with Jest as a testing framework then there’s no need to worry, it’s very simple to use and well documented. If you are experienced in testing with Jasmine, Jest will already feel very familiar to you.
First, if we haven’t already, we need to install typescript and Jest
Now we’ve installed Jest we can install ts-jest and it’s typings
We’re almost ready to test our code, but before we do, we need to configure our test environment. To do this, we need to generate our Jest config file:
You should now see a jest.config.js file in your project directory, and it should look something like this:
We’d like to add a few more configurations to get even more from our test setup. Firstly, we’re going to add code coverage by adding the following:
This will report out our code coverage in the console whenever we run the tests. In addition to this, it will also generate a report we can use in automated builds or as a visual representation of where the uncovered code branches, statements, functions and lines are located. These results will be created and stored in a new coverage directory, automatically generated when the tests are run.
We’d also like to have our tests have a coverage threshold so we can ensure code is tested to a sufficient standard. I’ve added a few extra options to my setup, here’s a quick overview of them:
If you’ve been following along thus far, your complete jest.config.js should look like this:
Now lets run the test and see the fruits of our labour:
You should see an output similar to the image below, (I already have tests to cover my code, so your coverage table will look different).
Now you’ve tested your code! Use the table to see your coverage for each of your project files and bump up the coverage. If you would like a more visual representation of the lines or branches you still need to cover, you can have a more detailed look by opening the coverage/Icov-report/index.html in your browser. That’s it! Don’t forget to look at the docs to get more insight into testing with Jest. Happy testing!
A Web, Tech, Football and Video Game enthusiast. Anything can be settled in smash! I’m a Software Engineer on the nerd.vision team with various front-end and back-end skills.