API reference

Mocking QueryBuilder

We can create queryBuilder in different ways. Let's see how we can create it:

dataSource.createQueryBuilder(User, 'user')
dataSource.getRepository(User).createQueryBuilder('user')
dataSource.manager.createQueryBuilder(User, 'user')

It doesn’t matter which approach you choose to fetch data using queryBuilder, mocking would remain the same. Here’s how you can mock it:

Example

it('should return the correct user', async () => {
  const typeorm = new MockTypeORM()
  typeorm.onMock(User).toReturn('user', 'getOne')

  const queryBuilder = dataSource.createQueryBuilder(User, 'user')
  const user = await queryBuilder.where('user.id = 1').select().getOne()

  expect(user).toEqual('user')
  // These are not necessary by the way. This is just to make you understand
  expect((queryBuilder.where as SinonStub).callCount).toEqual(1)
  expect((queryBuilder.select as SinonStub).callCount).toEqual(1)
  expect((queryBuilder.getOne as SinonStub).callCount).toEqual(1)
  expect((queryBuilder.getMany as SinonStub).callCount).toEqual(0) // just to test if we call this method or not
})

There is some gotcha here. You have to use one of these methods at the end of your queryBuilder in order to mock it correctly:

  • execute
  • getCount
  • getExists
  • getMany
  • getManyAndCount
  • getOne
  • getOneOrFail
  • getRawAndEntities
  • getRawMany
  • getRawOne
  • stream

This won't work!

This won’t work, e.g., as we haven’t added one of the above methods at the end of queryBuilder.

it('should return the correct user', async () => {
  const typeorm = new MockTypeORM()
  typeorm.onMock(User).toReturn('user', 'select')

  const queryBuilder = dataSource.createQueryBuilder(User, 'user')
  const user = await queryBuilder.where('user.id = 1').select()

  expect(user).toEqual('user')
})

If you want to support other methods, e.g., select, then create an issue in GitHub, and I’ll make it a part of the package as well. I am not very familiar with queryBuilder, so by looking at the documentation, I think we always need the above methods at the end of queryBuilder. But don’t worry, if you need other methods, I’ll quickly fix it for sure.

Previous
Mock Transaction