Introduction to ts-jest
ts-jest is an extremely useful TypeScript preprocessor with source map support for Jest, allowing seamless testing with TypeScript. It simplifies the process of testing TypeScript applications and provides powerful features to make the development workflow more efficient.
Installation
npm install --save-dev ts-jest @types/jest
Configuration
After installation, configure Jest to use ts-jest. Create or update the jest.config.js
file:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
Basic Usage
Here is an example showing how to write and test a simple TypeScript function:
Function Implementation (math.ts)
export const sum = (a: number, b: number): number => {
return a + b;
};
Test (math.test.ts)
import { sum } from './math';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Advanced Features
Mocking Functions
jest.mock('./moduleToMock', () => ({
functionToMock: jest.fn().mockReturnValue('mockValue'),
}));
Testing Asynchronous Code
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});
Snapshot Testing
test('renders correctly', () => {
const tree = renderer.create( ).toJSON();
expect(tree).toMatchSnapshot();
});
Example Application
Let’s create an example application using the covered APIs.
String Util (stringUtil.ts)
export const capitalize = (str: string): string => {
if (!str || typeof str !== 'string') return '';
return str.charAt(0).toUpperCase() + str.slice(1);
};
export const reverse = (str: string): string => {
if (!str || typeof str !== 'string') return '';
return str.split('').reverse().join('');
};
Test String Util (stringUtil.test.ts)
import { capitalize, reverse } from './stringUtil';
describe('capitalize', () => {
it('should capitalize the first letter', () => {
expect(capitalize('hello')).toBe('Hello');
});
it('should return empty string on non-string input', () => {
expect(capitalize(null)).toBe('');
});
});
describe('reverse', () => {
it('should reverse the string', () => {
expect(reverse('hello')).toBe('olleh');
});
it('should return empty string on non-string input', () => {
expect(reverse(null)).toBe('');
});
});
By using ts-jest, you can easily test TypeScript applications, ensuring better code quality and reducing errors in the production environment.
Hash: 79ee710a6ce528a371aa0f750dbef43f00f322ad5be9a38b32bbd287bfa4566b