Subscribe
Unit Testing Node.js TypeScript Applications with Jest
4 mins read

By: vishwesh

Unit Testing Node.js TypeScript Applications with Jest

Unit testing is an essential part of software development. It helps ensure that each part of the application works as expected and can be modified without affecting other parts. Node.js and TypeScript are two popular technologies used for building scalable and maintainable applications. Jest is a testing framework that simplifies the process of testing Node.js and TypeScript applications. In this article, we will discuss how to write unit tests for Node.js and TypeScript applications using Jest.

What is Jest?

Jest is a JavaScript testing framework developed by Facebook. It is designed to simplify the process of writing, running, and debugging unit tests. Jest is an open-source tool that provides built-in support for testing React, Node.js, and TypeScript applications. Jest has a wide range of features, including snapshot testing, mocking, and coverage reports. Jest is easy to set up and configure, making it an ideal choice for developers of all skill levels.

Setting up Jest

Before we can start writing tests with Jest, we need to set up our project to use Jest. We can do this by following these steps:

  1. Install Jest as a dev dependency:
npm install --save-dev jest
  1. Create a jest.config.js file in the root of your project:
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  modulePathIgnorePatterns: ['<rootDir>/dist/'],
  setupFilesAfterEnv: ['./jest.setup.ts'],
};

This configuration file tells Jest to use the TypeScript preset, run tests in a Node.js environment, ignore the dist/ folder, and use a setup file before running tests.

  1. Create a jest.setup.ts file in the root of your project:
import { MongoMemoryServer } from 'mongodb-memory-server';

let mongod: MongoMemoryServer;

beforeAll(async () => {
  mongod = await MongoMemoryServer.create();
});

afterAll(async () => {
  await mongod.stop();
});

This setup file starts an in-memory MongoDB server before running tests and stops the server after all tests have completed.

Writing Tests with Jest

Now that we have set up Jest in our project, we can start writing tests. In this section, we will go over some examples of how to write tests with Jest.

Testing a Function

Let's say we have a function sum that adds two numbers together. We can write a test for this function as follows:

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

test('sum function adds two numbers', () => {
  expect(sum(1, 2)).toBe(3);
});

In this test, we are using the expect function to assert that the sum function returns the expected result.

Testing an Asynchronous Function

Now let's say we have an asynchronous function getUserById that fetches a user by their ID from a database. We can write a test for this function as follows:

async function getUserById(id: string): Promise<{ id: string; name: string }> {
  // Assume this function fetches the user from a database
  return { id, name: 'John Doe' };
}

test('getUserById function fetches a user by ID', async () => {
  const user = await getUserById('123');
  expect(user.name).toBe('John Doe');
});

In this test, we are using the await keyword to wait for the getUserById function to return a value. We are then using the expect function to assert that the returned user has the expected name. 

Testing a Component

Now let's say we have a React component Button that renders a button with some text. We can write a test for this component as follows:

import React from 'react';
import { render } from '@testing-library/react';
import Button from './Button';

test('Button component renders the text', () => {
  const { getByText } = render(<Button text="Click me" />);
  expect(getByText('Click me')).toBeInTheDocument();
});

In this test, we are using the render function from the @testing-library/react library to render the Button component with the text "Click me". We are then using the getByText function to assert that the rendered component contains the text "Click me".

Mocking Dependencies

Sometimes our functions and components have dependencies that we don't want to include in our tests. In these cases, we can use Jest's mocking functionality to create fake versions of these dependencies. Let's say we have a function getWeather that fetches the current weather from an external API. We can write a test for this function that mocks the external API as follows:

async function getWeather(): Promise<string> {
  const response = await fetch('https://api.weather.com/current');
  const data = await response.json();
  return data.weather;
}

test('getWeather function returns the current weather', async () => {
  const mockWeather = 'sunny';
  jest.spyOn(window, 'fetch').mockResolvedValueOnce({
    json: async () => ({ weather: mockWeather }),
  } as Response);

  const weather = await getWeather();
  expect(weather).toBe(mockWeather);
});

In this test, we are using Jest's spyOn function to create a fake fetch function that returns the weather we want to test. We are then using the expect function to assert that the getWeather function returns the expected weather.

Conclusion

In this article, we discussed how to write unit tests for Node.js and TypeScript applications using Jest. We covered how to set up Jest, how to write tests for functions and components, how to test asynchronous code, and how to mock dependencies. Jest is a powerful and easy-to-use testing framework that can help you ensure the quality of your code and catch bugs before they make it to production. With Jest, you can write tests that are concise, reliable, and easy to maintain.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories