WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Expert · question 79 of 100

Can you explain how to write unit tests for TypeScript code?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

Writing unit tests for TypeScript code is a crucial step for ensuring that your code works correctly and is free from bugs. This will also help with maintainability and collaboration. The most popular testing frameworks used in TypeScript projects are Jest and Mocha, along with assertion libraries like Chai.

In this answer, I will explain how to write unit tests for TypeScript code using Jest, which is the most popular choice.

First, you need to set up your TypeScript project for testing with Jest.

1. **Install necessary dependencies:**

npm install --save-dev jest @types/jest ts-jest typescript

You can also use ‘yarn‘ to install the packages if you prefer:

yarn add --dev jest @types/jest ts-jest typescript

2. **Create a Jest configuration file:**

Create a new file in the root of your project called ‘jest.config.js‘ and copy the following content:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

3. **Update package.json:**

Add the following scripts for running tests and generating coverage reports in your ‘package.json‘ file:

"scripts": {
  "test": "jest",
  "test:coverage": "jest --coverage",
  ...
}

4. **Write your tests:**

Now, let’s write a simple TypeScript function and a corresponding unit test.

File: ‘add.ts‘ (The function to be tested)

export function add(a: number, b: number): number {
  return a + b;
}

File: ‘add.test.ts‘ (The unit test file)

import { add } from './add';

describe('add', () => {
  test('it should add two numbers correctly', () => {
    const result = add(3, 4);
    expect(result).toBe(7);
  });

  test('it should handle negative numbers', () => {
    const result = add(-2, 5);
    expect(result).toBe(3);
  });
});

In the test file, we import the ‘add‘ function, and then we use ‘describe‘ and ‘test‘ functions from Jest to organize and define our test cases. Inside each test case, we use ‘expect‘ along with a Jest matcher (e.g., ‘toBe‘, ‘toEqual‘, ‘toBeFalsy‘, etc.) to make assertions on the behavior of the ‘add‘ function.

5. **Run the tests:**

To run the tests, use the following command:

npm test

If everything is set up correctly, you should see output indicating that the tests passed.

Here’s a chart illustrating the testing process using Jest:

In summary, to write unit tests for TypeScript code, you can follow these steps:

1. Install necessary dependencies for testing (e.g., Jest, TypeScript, and other TypeScript type definitions).

2. Configure your TypeScript project for testing with Jest.

3. Update your ‘package.json‘ to include test scripts.

4. Write your TypeScript tests using ‘describe‘, ‘test‘, and ‘expect‘ functions from Jest.

5. Run the tests using the ‘npm test‘ command.

By following these steps, you can ensure the correctness and quality of your TypeScript code and make your code maintainable and collaborative.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics