API reference

Mocking EntityManager

There is another way we can call TypeORM methods, i.e., Entity Manager. Here’s how you can do it, e.g.,

Example 1

test('find()', async () => {
  const typeorm = new MockTypeORM()
  typeorm.onMock(User).toReturn(['user'], 'find')

  const users = await dataSource.manager.find(User, {})

  expect(users).toEqual(['user'])
})

So, mocking would be the same; we are just fetching users via Entity Manager.

Example 2

Let's take another example where we create a new user using two TypeORM methods:

  1. create
  2. save
test('create a user', async () => {
  const typeorm = new MockTypeORM()
  typeorm.onMock(User).toReturn({ id: 'newId' }, 'save')

  const user = dataSource.manager.create(User, { id: '1' })
  const savedUser = await dataSource.manager.save(user)

  expect(savedUser).toEqual({ id: 'newId' })
})

As you can see, I added mock data for the save method. It’s similar to what we did before, so nothing changed; we just added a different function like save(). So, when save is called, it will return the mock data.

Previous
Mock DataSource