如何破坏NestJS中的测试模块?

问题描述 投票:0回答:1

我真的无法进入测试世界。我正在尝试编写一些简单的测试来开始。这是我的测试:

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,
        });
    });
  });
});

当我尝试创建新的测试模块时,问题就开始了(每次测试之前都会发生这种情况),因此会抱怨仍然活跃的数据库连接(在第一次测试之后):

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

那么,我怎样才能在每次测试后从数据库中删除所有记录?

node.js unit-testing typescript typeorm nestjs
1个回答
0
投票

在创建具有相同数据库连接的新应用程序之前,您必须使用close()应用程序。您可以通过调用synchronize(true)来清除数据库。

import { getConnection } from 'typeorm';

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

作为替代方案,您还可以通过设置typeorm来允许keepConnectionAlive重用现有的数据库连接。 (你可能只想在测试中这样做,例如检查process.env.NODE_ENV。)

TypeOrmModule.forRoot({
  // ...
  keepConnectionAlive: true
})
© www.soinside.com 2019 - 2024. All rights reserved.