【问题标题】:How to destroy test module in NestJS?如何销毁 NestJS 中的测试模块?
【发布时间】:2023-03-24 11:56:01
【问题描述】:

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

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: 'mail@userland.com',
        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,
        });
    });
  });
});

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

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

顺便问一下,如何在每次测试后从数据库中删除所有记录?

【问题讨论】:

  • ...通过删除添加的记录并关闭连接?
  • 这条路线对我来说非常糟糕。
  • 好吧,如果您使用的是真正的数据库,它是唯一的。大多数情况下,单元测试假定您模拟除已测试单元之外的所有内容。
  • 我在使用 MongoDB,所以没有事务,这很糟糕。
  • 测试不应该影响现有的数据库,应该有一个专用的测试数据库,可以随时删除。但同样,这适用于 e2e 测试。对于单元测试,使用真实数据库没有意义。模拟除控制器之外的所有内容。

标签: node.js unit-testing typescript typeorm nestjs


【解决方案1】:

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

import { getConnection } from 'typeorm';

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

您也可以通过设置keepConnectionAlive 来允许typeorm 重用现有的数据库连接。 (您可能只想在测试中执行此操作,例如通过检查 process.env.NODE_ENV。)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2021-07-15
    • 2020-06-22
    • 2021-12-03
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多