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:
This, which contains an import, will not work:
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:
- Install VSCode plugins to improve the unit test experience
- Install the npm packages necessary to let you import from .ts files in your CRA unit tests
- 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:
- Test Explorer IU
- This will give us the "Run" and "Debug" links above every test that it detects and also provide a test explorer in VSCode comparable to that available in Visual Studio
- This is the base plugin, after which you install an adapter for the desired test framework
- Jest Test Explorer
- This is the adapter for Jest
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:
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:
- @testing-library/jest-dom
- @testing-library/react
- @testing-library/user-event
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: