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

时间:2018-03-10 14:39:34

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

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

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

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

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

顺便说一句,我怎样才能在每次测试后删除数据库中的所有记录?

1 个答案:

答案 0 :(得分: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
})