#Is there a way to mock `transactionalEntityManager` inside `DataSource.transaction`?

4 messages · Page 1 of 1 (latest)

hallow monolith
#

Hello. I'm using transactions in my app and in one case I'm passing transactionalEntityManager as an argument to another method form other service than the one I use DataSource in. As an example:

await myDataSource.transaction(async (transactionalEntityManager) => { // execute queries using transactionalEntityManager in the current service // and also passin as an argument the manager and callin a method from other service await this.anotherInjectedService.doDataBaseAction(transactionalEntityManager, someId, someData) })

So the problem occurs when I want to test that anotherInjectedService's method doDataBaseAction and don't get the idea of how can I mock the transactionalEntityManager in that test. I'm using jest by the way and mentioning unit tests.

hallow monolith
#

Can I do it like this ?

const teManagerMock = {save: jest.fn(), update: jest.fn(), delete: jest.fn()};

and then just pass it as an argument? It works correclty, but I don't know if this is a good approach or not.

deft galleon
#

Yes, I did this in my unit tests like this:

      const mockEntityManager = createMock<EntityManager>({ 
         create: jest.fn().mockReturnValue(createdDevice), 
         save: jest.fn().mockResolvedValue(createdDevice), 
       }); 
       const transactionMock = jest.fn(async (passedFunction) => await passedFunction(mockEntityManager)); 
       jest.spyOn(dataSource, 'transaction').mockImplementation(transactionMock);
#

Note I am using golevelup's ts-jest package