2

I have a service on NestJS 6. I use TypeORM for work with MySQL.

When I try to write unit-tests for method with @Transaction() and @TransactionManager() decorators, I get the error: ConnectionNotFoundError: Connection "default" was not found..

@Put(':id')
@Transaction()
update(
  @Body() someData: SomeDto,
  @Param('id') id: number,
  @UserDecorator() user: User,
  @TransactionManager() manager: EntityManager,
) {
  return this.someService.update(id, someData, user, manager);
}

My test:

beforeEach(async () => {
  manager = new EntityManager(null);
  someService = new SomeService();
  someController = new SomeController(someService);
});

describe('update', () => {
  it('should update', async () => {
    jest.spyOn(someService, 'update').mockResolvedValue(result);

    await expect(await someController.update(someData, 1, user, manager)).toBe(result);
    expect(someService.update).toBeCalledWith(1, someDto, user, manager);
  });
});

Is there a better way for write and test it?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Sergei Krivochenko
  • 567
  • 1
  • 6
  • 21

1 Answers1

1

Using typeorm's @Transaction like this goes against nest's DI and hence makes testing very hard, see this issue: github.com/nestjs/typeorm/issues/57 Official docs on how to do transactions in nest will follow soon.

The above suggestion from Kim Kern worked for me. I replaced @Transaction by connection.transaction(cb) as recommended by NestJS docs and now I could properly mock TypeORM stuff and test in isolation.

Yago Tomé
  • 46
  • 4