odavid / typeorm-transactional-cls-hooked

A Transactional Method Decorator for typeorm that uses cls-hooked to handle and propagate transactions between different repositories and service methods. Inpired by Spring Trasnactional Annotation and Sequelize CLS
MIT License
524 stars 86 forks source link

Testing Error initializeTransactionalContext() #89

Open sgentile opened 3 years ago

sgentile commented 3 years ago

So I'm using Jest and we are strictly doing unit tests -

I used the example

jest.mock('typeorm-transactional-cls-hooked', () => ({
            Transactional: () => () => ({}),
            BaseRepository: class {},
        }));

But it errors on initializeTransactionalContext(). Where would initializeTransactionalContext be used within a jest unit test ?

sgentile commented 3 years ago

When I added this it gives this message.

"ConnectionNotFoundError: Connection "default" was not found."

So is seems the mock is not handling mocking out the connection. ?

Elithsar commented 3 years ago

Same problem here.

I can't figure out how to mock this @Transactional decorator.

Here is the used code.

let myService: MyService;
let myRepository: MyRepository;

  beforeEach(async () => {
    jest.mock('typeorm-transactional-cls-hooked', () => ({
      Transactional: () => () => ({}),
      BaseRepository: class {},
    }));
    initializeTransactionalContext();

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        MyService,
        MyRepository,
        {
          provide: getRepositoryToken(MyRepository),
          useClass: MyRepositoryFake
        }
      ],
    }).compile();

    myService = module.get(MyService);
    myRepository = module.get(MyRepository);
  });

Am I doing something wrong ?

psteinroe commented 3 years ago

I was able to mock it using

jest.mock('typeorm-transactional-cls-hooked', () => ({
  Transactional: () => jest.fn(),
}));