Unit testing is a fundamental best practice in software development, enabling you to ensure that your code functions as intended before it goes into production. Using TypeScript, a statically typed superset of JavaScript, can help catch errors early and allow for a more maintainable codebase. In this blog, we'll dive deep into the intricacies of unit testing with TypeScript, illustrating the process through clear examples.
Unit testing is the process of testing individual components of your code (units) in isolation to ensure they work correctly. It's aimed at identifying bugs as early as possible, simplifying future code changes, and ultimately increasing the quality and reliability of your application.
Before we embark on our unit testing journey, let's set up our environment. For this, we'll use a popular testing framework, Jest, which has excellent TypeScript support and a vibrant community.
Make sure you have Node.js and npm installed on your machine. Then, create a new directory for your TypeScript project and navigate to it:
mkdir ts-unit-testing-example cd ts-unit-testing-example
Run the following commands to set up your project and install necessary dependencies:
npm init -y npm install --save-dev typescript jest ts-jest @types/jest
Create a tsconfig.json
file in the root of your project:
{ "compilerOptions": { "target": "es6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"] }
In your package.json
, add the following to configure Jest:
"jest": { "preset": "ts-jest", "testEnvironment": "node" }
Finally, create your source folder and a simple TypeScript file to test:
mkdir src touch src/calculator.ts
Add the following simple calculator functions to calculator.ts
:
export function add(a: number, b: number): number { return a + b; } export function subtract(a: number, b: number): number { return a - b; }
Next, let's create a test file to check if our calculator functions work as expected. In the src
folder, create a file named calculator.test.ts
:
touch src/calculator.test.ts
Inside calculator.test.ts
, write the following tests for both functions:
import { add, subtract } from './calculator'; describe('Calculator Tests', () => { test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3); }); test('subtracts 5 - 2 to equal 3', () => { expect(subtract(5, 2)).toBe(3); }); });
toBe()
to validate the expected outcome.With everything in place, you can now run your tests using the following command:
npx jest
You should see the results in your terminal, indicating that both tests have passed successfully!
Often in applications, you'll encounter asynchronous behavior that can complicate testing. Jest provides built-in utilities for testing asynchronous code.
Here's how you can test an asynchronous function in TypeScript. Let's modify our calculator.ts
to include an asynchronous function:
export async function multiplyAsync(a: number, b: number): Promise<number> { return new Promise((resolve) => { setTimeout(() => resolve(a * b), 1000); }); }
Now, update calculator.test.ts
to add a test for multiplyAsync
:
test('multiplies 3 * 4 to equal 12 asynchronously', async () => { await expect(multiplyAsync(3, 4)).resolves.toBe(12); });
async
before the callback function to handle promises.resolves
matcher in expect
lets you assert that the promise should resolve to a particular value.By understanding these concepts and employing them in your TypeScript projects, you can build robust applications with confidence. In unit testing, the journey is to test thoroughly, understand your code, and ensure reliability every step of the way. Happy testing!
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript
17/10/2024 | TypeScript