Tymur Valiiev
Tymur Valiiev

Reputation: 729

How to destroy test module in NestJS?

I really cant get into testing world. I'm trying to write some simple tests to get started. Here is my test:

describe('UsersController', () => {
  let usersController: UsersController;
  let usersService: UsersService;
  let module = null;
  let connection: Connection;

  beforeEach(async () => {
      module = await Test.createTestingModule({
        modules: [DatabaseModule, LibrariesModule],
        controllers: [UsersController],
        components: [UsersService, ...usersProviders],
      })
      // TODO: provide testing config here instead of separate .env.test file
      // .overrideComponent(constants.config)
      // .useValue()
        .compile();
      connection = module.select(DatabaseModule).get(constants.DBConnectionToken);
      usersService = module.get(UsersService);
      usersController = module.get(UsersController);
  });

  afterEach(async () => {
    jest.resetAllMocks();
  });

  describe('getAllUsers', () => {
    it('should return an array of users', async () => {
      const result = [];

      expect(await usersController.getAllUsers())
        .toEqual([]);
    });
  });

  describe('createUser', () => {
    it('should create a user with valid credentials', async () => {
      const newUser: CreateUserDto = {
        email: '[email protected]',
        password: 'password',
        name: 'sample user',
      };
      const newUserId = '123';
      jest.spyOn(usersService, 'createUser').mockImplementation(async () => ({user_id: newUserId}));
      const res = await usersController.createUser(newUser);
      expect(res)
        .toEqual( {
          user_id: newUserId,
        });
    });
  });
});

Problems start when i'm trying to create new testing module (it happens every time before each test) , typeorm complaining about still active database connection (after first test):

Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.

By the way, how i can delete all records from the database after each test?

Upvotes: 1

Views: 7276

Answers (1)

Kim Kern
Kim Kern

Reputation: 60457

You have to close() the application before you create a new one with the same database connection. You can clear the database by calling synchronize(true).

import { getConnection } from 'typeorm';

afterEach(async () => {
  if (module) {
    // drop database
    await getConnection().synchronize(true);
    // close database connections
    await module.close();
  }
});

As an alternative, you can also allow typeorm to reuse an existing database connection by setting keepConnectionAlive. (You probably want to do this only in tests, e.g. by checking process.env.NODE_ENV.)

TypeOrmModule.forRoot({
  // ...
  keepConnectionAlive: true
})

Upvotes: 2

Related Questions