Blog

Setup Jest in CRA to enable debugging & breakpoints when importing from plain Typescript files in VSCode

Published:

The Problem

Out of the box, create-react-app only installs the required Jest packages to enable us to debug JSX / TSX files. This is a problem for those who want to create a domain model in the frontend, which will require creating plain old .ts Typescript files.

Using the default settings, I found that it was possible to run a very basic test but not to run a test that contained any imports from a .ts file.

So whilst this might work:

https://i.imgur.com/3irczwy.png

This, which contains an import, will not work:

https://i.imgur.com/3JIJjR2.png

The Solution

This obviously isn't much good, so we're going to fix this issue. While we're at it, we might as well install a few plugins that improve the TDD experience in VSCode.

This article will show you how to:

  1. Install VSCode plugins to improve the unit test experience
  2. Install the npm packages necessary to let you import from .ts files in your CRA unit tests
  3. Add the required config for the new npm packages

1. Install the necessary VSCode plugins

If you want the little "Run" and "Debug" buttons that you can see in the above screenshots, we'll first need to install the following VSCode extensions:

Both of these plugins can be installed via the Visual Studio Marketplace or by searching for the in the VSCode extensions pane.

The end result is this neat looking test pane in VSCode:

https://i.imgur.com/CggUX9P.png


2. Install npm packages necessary to enable imports from .ts files for your CRA unit tests

The problem with the default CRA setup is that it only gives us the following Jest packages out of the box:

It looks like CRA makes the assumption that we'll only be testing React components (i.e. .tsx files). In order to run Jest against standalone .ts files, we to install actual jest along with ts-jest.

Run the following command to do that:

npm install jest ts-jest --save-dev

3. Add the required config for the new npm packages

Finally, we need to add a jest.config.js file to the root of our project. We can automatically generate one by running the following command:

npx ts-jest config:init

This will give us the following file:

jest.config.js:

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
};

Testing it

Let's go back to that initial test with an import from the beginning.

If I click the newly added "Debug" link above my test, I can see that the breakpoint is getting hit as the debugger is working as expected:

https://i.imgur.com/V3VP8Oe.png