Unit Testing & TDD
Unit testing and test-driven development (TDD) are essential practices for developing maintainable and robust applications. In this tutorial, we'll introduce you to unit testing in TypeScript using Jest, a popular testing library.
Installing Jest and TypeScript Setup
To start, install Jest and its TypeScript dependencies:
npm install --save-dev jest ts-jest @types/jest typescript
Create a jest.config.js
file in your project root and add the following configuration:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
Writing a Basic Test
Let's create a simple TypeScript function to test. Create a sum.ts
file with the following code:
export function sum(a: number, b: number): number {
return a + b;
}
Now, create a test file named sum.test.ts
:
import { sum } from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
To run the test, add the following script to your package.json
:
"scripts": {
"test": "jest"
}
Run the test using npm test
.
Test-driven Development (TDD)
TDD is a development practice where you write tests before implementing the functionality. The process usually follows these steps:
- Write a failing test.
- Implement the code to make the test pass.
- Refactor the code, if necessary.
Let's use TDD to implement a subtract
function. First, write a failing test in subtract.test.ts
:
import { subtract } from './subtract';
test('subtracts 5 - 3 to equal 2', () => {
expect(subtract(5, 3)).toBe(2);
});
Run the test and see it fail. Now, implement the subtract function in subtract.ts
:
export function subtract(a: number, b: number): number {
return a - b;
}
Run the test again, and it should pass. Refactor the code if needed.
Conclusion
In this tutorial, we've learned the basics of unit testing and test-driven development in TypeScript using Jest. By following these practices, you can improve the quality and maintainability of your code.