How to Test TypeScript with Jest?
Jest is a popular JavaScript testing framework maintained by Facebook and is widely used for testing React applications. However, it's not limited to React or JavaScript alone. it also works seamlessly with TypeScript, providing a robust environment for writing and running tests. Testing TypeScript with Jest involves setting up the environment, writing test cases, and running these tests to ensure your TypeScript code behaves as expected.
These are the following topics that we are going to discuss:
Table of Content
Setting up Jest with TypeScript
Before you can start writing tests, you must set up your project using Jest with TypeScript. This involves installing necessary packages and configuring Jest.
Step 1: Get started with nodejs and Install the necessary packages
npm init -y
npm install --save-dev jest @types/jest ts-jest typescript
Step 2: Create a jest.config.js file
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
Step 3: Add a tsconfig.json file if you don't already have one
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Step 4: Once the setup is complete, you can start writing tests. Jest allows you to write test cases using its built-in functions like describe, test, it, expect, etc.
Step 5: Create a TypeScript file, say sum.ts
export const sum = (a: number, b: number): number => {
return a + b;
};
Step 6: Create a test file, sum.test.ts
import { sum } from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Note: Running the tests is straightforward using the Jest command-line interface. Jest provides detailed feedback on your tests, showing which tests passed, failed, and why.
Step 7: Run your tests using the following command
npx jest
Output:

Case 1: Testing Mock Functions using Jest
Jest provides powerful mocking capabilities, allowing you to mock functions, modules, and timers. This is useful for isolating the code under test and controlling its dependencies.
Example: This example shows the testing of function.
// sum.ts
export const fetchData = (callback: (data: string) => void) => {
setTimeout(() => {
callback('peanut butter');
}, 1000);
};
// sum.test.ts
import { fetchData } from './sum';
test('fetchData calls callback with "peanut butter"', done => {
function callback(data: string) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
Output:

Case 2: Testing Asynchronous Code
Testing asynchronous code can be challenging, but Jest makes it easier with support for async functions, promises, and callback-based code.
Example: This example shows the testing of Asynchronous function.
// sum.ts
export const fetchDataPromise = (): Promise<string> => {
return new Promise(resolve => {
setTimeout(() => {
resolve('peanut butter');
}, 1000);
});
};
// sum.test.ts
import { fetchDataPromise } from './sum';
test('the data is peanut butter', async () => {
const data = await fetchDataPromise();
expect(data).toBe('peanut butter');
});
Output:
