nemoxi
nemoxi

Reputation: 620

The test with JestJS that closes the application does not work

Friends, I have a problem!

I'm testing my API with NestJS. I'm using Jest for the test. Unfortunately, I am encountering the following error:

TypeError: Cannot read properties of undefined (reading 'close')

This error is very explicit but I don't see where it could come from.

Would you have an idea?

My current code :

import * as pactum from 'pactum';
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { PrismaService } from '../src/prisma/prisma.service';
import { AuthDto } from '../src/auth/dto';

describe('App e2e', () => {
  let app: INestApplication;
  let prisma: PrismaService;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    const app = moduleRef.createNestApplication();
    app.useGlobalPipes(
      new ValidationPipe({
        whitelist: true,
      }),
    );
    await app.init();
    await app.listen(3334);

    prisma = app.get(PrismaService);
    await prisma.cleanDatabase();
  });

  afterAll(async () => {
    console.log('Closing server');
    await app.close(); // <------------- THE PROBLEM ARISES HERE.
  });

  describe('Auth', () => {
    describe('Signup', () => {
      it('should signup a user', () => {
        const dto: AuthDto = {
          email: '[email protected]',
          password: '1234',
        };
        return pactum
          .spec()
          .post('http://localhost:3333/auth/signup')
          .withBody(dto)
          .expectStatus(201);
      });
    });
    describe('Signin', () => {
      it.todo('should signin a user');
    });
  });
});

Upvotes: 0

Views: 1010

Answers (1)

n1md7
n1md7

Reputation: 3469

You are mixing two variables in different scopes.

let app: INestApplication; is upper scope one which you are actually using, since it does not have any value assigned it is undefined. The inner one is different because you are defining inside another scope.

A solution is very simple, just remove const from const app = moduleRef.createNestApplication();

Upvotes: 2

Related Questions