Unit testing TypeScript with Jest: Part One - Project setup
Tags: testing, typescript, webdev, programming
Published: 2022-03-11 19:09:42


## Configure a TypeScript project with Jest

The TypeScript programming language enables developers to be more productive by providing us tools to catch errors early on in the process: a powerful type system, additional syntax and tight IDE integration. Writing unit tests to verify discrete parts of our TypeScript code should also be part of the standard development practice. In this tutorial, we will be setting up a new TypeScript project and dive into setting up unit testing with [Jest](https://jestjs.io/) as our framework of choice.

What you will need to get started are:
- [Node.js](https://nodejs.org/en/) version 17
- IDE of choice (e.g. Visual Studio Code)

### 1. Start a new project with required dependencies
We will create a TypeScript project from scratch. Let’s first create the directories for our project:
```bash
mkdir typescript-jest
cd typescript-jest
mkdir src
mkdir test
```

We are going to use NPM as our package manager. When you install Node.js, the NPM package manager is included by default. Let’s initialize our project with NPM:
```bash
npm init -y
```

A Node.js project produces a bunch of files and directories that don’t need to be included for tracking in Git. We can create a boilerplate **.gitignore** file in our project specifically for Node.js as follows:
```bash
npx gitignore node
```
The NPM tool also includes the npx command. We are using the npx command in this scenario so that we can run the gitignore command without having to install it globally.

Now we’re going to install the required dependencies for TypeScript and Jest as follows:
```bash
npm i -D typescript jest ts-jest @types/jest
```

We’re using the `-D` flag in the command to signify that these packages need to be installed as a development dependency. This means that these packages are required for development.

### 2. Configure TypeScript and starter code
Next up, we need to initialize and configure our TypeScript project to our liking. We will use the built-in Typescript compiler tsc to initialize the project. This can be done as follows:
```bash
npx tsc --init
```

The output of this command will look like this:
![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gusckq6l4sygcm1ev0vu.png)

The `--init` flag of the `tsc` command will create a `tsconfig.json` file in our project directory.

Next up we will add three parameters to `tsconfig.json` to configure how the TypeScript compiler behaves:
- **rootDir**: directory where the source code will be
- **outDir**: directory where the transpiled JS code will be
- **sourceMap**: easier debugging referring to TS files instead of transpiled JS files

Your `tsconfig.json` should look like this after adding these three parameters:
{% gist https://gist.github.com/duncanlew/f0372785a450db4edabcf556e60aa129 %}

Now that we are done configuring our TypeScript compiler, let’s write some TypeScript code. Inside the src directory create a `math.ts` file with the following contents:
{% gist https://gist.github.com/duncanlew/e69218af982b0b3a9091569613e4682d %}

### 3. Configure Jest and starter tests
Our testing framework of choice is [Jest](https://jestjs.io/). The main reasons for using Jest are its simple set-up, lightning-fast execution and built-in matchers. To sweeten the deal even more is its native TypeScript support.

By default, Jest can run without any configuration. However, we’re going to be writing our tests in TypeScript, which requires a small configuration to transpile TypeScript with **ts-jest**. The package **ts-jest** can create a default configuration as follows:
```bash
npx ts-jest config:init
```
The next step is to add the test command for Jest in our package.json file:
```json
"scripts": {
    "test": "jest"
},
```

Now that Jest is all set up, we can finally write our unit tests! By default, Jest is going to run all files ending in `test.ts`. Let’s create two simple test cases in the `test` directory for the math functions. We will name this test file `math.test.ts` and its contents should look like this:
{% gist https://gist.github.com/duncanlew/ea3dfea7bb791e0aee1f904996e9385b %}


### 4. Run the unit tests
We have written our math functions in src/math.ts. We have set up Jest using TypeScript and created our first test file: test/math.test.ts. The only thing left to do is to run the tests. We’ve added a test command in the package.json file. We can then run the test like this:
```bash
npm test
```

The output of Jest should look like this:
![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hnedtzi00tbb7b83von1.png)

Try playing around with the test cases in the test directory and check how the output changes. We can change the expected number in a test file and see what the output of a failed test looks like.
![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lq8h7u780rcx46ubabpr.png)
 

We can see that Jest provides very clear error messages on which test failed and where this failure occurs and how you can actively fix it.

### Conclusion
We have walked through how to set up a TypeScript project in which the unit tests are run by the Jest framework. Jest proved to be very easy to set up for a TypeScript project and also outputs valuable information for debugging purposes. Writing tests to verify all existing and new business logic of our application should be an integral part of our development job.

In this part one series, we’ve only covered how to run the tests locally. Ideally, you’d want this to run every time before changes are accepted into your codebase. Check out [part 2](https://dev.to/duncanlew/unit-testing-typescript-with-jest-part-two-cicd-pipeline-setup-with-github-actions-469p) to see how these unit tests can be automated.

The full source code of this project can be found on [GitHub](https://github.com/duncanlew/demo-jest-typescript).

If the content was helpful, feel free to support me [here](https://www.buymeacoffee.com/duncanlew):
<a href="https://www.buymeacoffee.com/duncanlew" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>