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: '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.

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

4

1 回答 1

2

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
})
于 2019-04-03T15:17:24.647 回答