NestJS unit testing

NestJS unit testing

This tutorial is a deep dive into unit testing in NestJS (including mocking with test doubles).

To get the most out of this tutorial, I recommend coding along with npm run test:watch running locally to see the tests we write in action!

If you're an absolute beginner with unit testing as a practice as well as unit testing in NestJS, this section is for you! Jump to the next section if you're interested to learn about test doubles and mocking.

We're going to build a service with some basic CRUD functionality for handling Tweets and then write some unit tests for them.

Let's start by adding a module called tweets

nest g module tweets        

And then add a tweets service:

nest g service tweets
        

Running these 2 commands will create a directory called tweets with 3 files inside:

src / tweets / tweets.module.ts
tweets.service.spec.ts
tweets.service.ts
        

Open up the test file that NestJS created for us called tweets.service.spec.ts, which will look like this:

import { Test, TestingModule } from '@nestjs/testing';
import { TweetsService } from './tweets.service';

describe('TweetsService', () => {
  let service: TweetsService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [TweetsService],
    }).compile();

    service = module.get<TweetsService>(TweetsService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});
        

If you haven't done so already, make sure you're running your tests locally with this command:

npm run test:watch
        

Your terminal should output the following:

Article content

Nice work! The unit tests are now running with hot reloading. Any changes you make to your code will re-run the tests.


Agustinus Theodorus

Experienced Rust Developer, ZK/ECC, Solutions Architect

1y

What's comprehensive about this?

To view or add a comment, sign in

More articles by Syed Bilal Ali

Insights from the community

Others also viewed

Explore topics