API reference
Mocking Transactions
Mocking will also work for transactions both when creating a transaction from dataSource and from queryRunner. It will also work if we are using queryBuilder and some other scenarios as well.
Example with Callback
Here’s how you can test the transactions when creating directly from dataSource, e.g.,
it('should run method inside transaction', async () => {
const mockUsers = ['user']
const typeorm = new MockTypeORM()
typeorm.onMock(User).toReturn(mockUsers, 'find')
let users: any
await dataSource.transaction(async (manager) => {
users = await manager.find(User, {})
})
expect(users).toEqual(mockUsers)
})
As you can see, mocking still remains the same; nothing changed here.
Example with QueryRunner
Let's see a transaction with queryRunner.
it('should return correct payload with manager methods', async () => {
const mockUser = { id: '1', name: 'a' }
const typeorm = new MockTypeORM()
typeorm.onMock(User).toReturn(mockUser, 'findOne')
const queryRunner = dataSource.createQueryRunner()
await queryRunner.connect()
await queryRunner.startTransaction()
const user = await queryRunner.manager.findOne(User, { where: {} })
await queryRunner.commitTransaction()
await queryRunner.release()
expect(user).toEqual(mockUser)
})