Using ts-jest allows you to run TypeScript tests with Jest seamlessly. It provides a way to compile TypeScript files on the fly, making it easier to write and execute tests without needing a separate build step. Below, I will outline the steps to set up ts-jest, including practical examples, best practices, and common mistakes to avoid.
To get started, you need to install ts-jest along with Jest and TypeScript. You can do this using npm or yarn:
npm install --save-dev jest ts-jest @types/jest typescript
Alternatively, if you are using yarn:
yarn add --dev jest ts-jest @types/jest typescript
After installation, you need to configure Jest to use ts-jest. This can be done by creating a Jest configuration file, typically named jest.config.js or jest.config.ts. Below is an example of a basic configuration:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.test.ts', '**/?(*.)+(spec|test).ts'],
};
Ensure that your tsconfig.json is properly set up. Here’s a basic example:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*", "tests/**/*"]
}
With the configuration in place, you can start writing tests. Here’s a simple example of a TypeScript function and its corresponding test:
// src/sum.ts
export const sum = (a: number, b: number): number => a + b;
// tests/sum.test.ts
import { sum } from '../src/sum';
describe('sum function', () => {
it('should return the sum of two numbers', () => {
expect(sum(1, 2)).toBe(3);
});
});
tests or __tests__.@types/jest.tsconfig.json correctly can result in compilation errors. Ensure that your settings align with your project needs.By following these guidelines, you can effectively use ts-jest to enhance your testing workflow in TypeScript projects. This setup not only streamlines the testing process but also leverages TypeScript's strengths to ensure your code is both reliable and maintainable.