How To Run Jest Unit Tests In a Typescript Project
Follow these steps to set up Jest unit tests in a TypeScript project.
IMPORTANT
This guide uses the ts-jest npm library to simplify the setup. As described on the npm page, ts-jest is a Jest transformer with source map support that allows you to use Jest to test projects written in TypeScript.
Step 1 – Create your project folder and initialize npm
Run the following commands to create a new project folder and initialize npm. Replace my-project with the name of your project.
cd my-project
npm init -y
Step 2 – Install prerequsites
Run the following command to install the necessary npm packages.
Step 3 – Setup the typescript project
Run the following command to create a tsconfig.json file in your project folder.
Step 4 – Configure Jest
Run the following command to create a Jest configuration file that is compatible with Typescript.
This command will create the jest.config.js file in your project folder.
Step 5 – Create some code and unit tests
Create the src/calculator.ts file as below:
return a + b;
}
Create the tests for the calculator in the test/calculator.spec.ts file as below:
describe(“Calculator tests“, () => {
it(“should add two numbers“, () => {
expect(add(1, 2)).toBe(3);
});
})
Step 6 – Run the tests
Run the tests from the command line as below:
You should see these results in the console:
PASS test/calculator.spec.ts
Calculator tests
✓ should add two numbers (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.385 s, estimated 2 s
Ran all test suites.
Step 7 – Add test script in package.json file
To run the tests via the npm test command you can change the scripts section in the package.json file to look like this:
“test”: “jest”
}
Now you should be able to run the tests with the npm test command and get the same output in the console.