Core Concepts

Basic Mocking

Now that you understand how mocking works and how to restore it to its original behavior, let's see how to mock actual methods like find(), findOne(), save(), etc.

Example

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

    const userRepo = dataSource.getRepository(User)
    const users = await userRepo.find()

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

Helper Functions

  • onMock()
  • resetAll()
  • restore()

onMock()

onMock() accepts a repository class or string (repository name). This is useful when using EntitySchema in JavaScript.

const typeorm = new MockTypeORM()
typeorm.onMock(User) // repository class
typeorm.onMock('User') // repository name as string

onMock() returns this to allow method chaining:

typeorm.onMock(User).toReturn([], 'find').toReturn({ id: '1' }, 'findOne')

reset()

onMock() also returns a reset() method to reset mock data:

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

    const userRepo = dataSource.getRepository(User)
    const users = await userRepo.find()

    expect(users).toEqual({})
  })
})

As you can see, I reset the mock data for the find method that we set using the toReturn() function. So when the find() method is called and no mock data is found for that method, it will return {} by default. That’s what we are expecting in our test assertion, meaning we have successfully reset the find method.

To reset everything at the repository level:

describe('test suites', () => {
  it('test', async () => {
    const typeorm = new MockTypeORM()
    typeorm
      .onMock(User)
      .toReturn(['user'], 'find')
      .toReturn({ id: '1' }, 'findOne')
      .reset()

    const userRepo = dataSource.getRepository(User)
    const users = await userRepo.find()
    const user = await userRepo.findOne({})

    expect(users).toEqual({})
    expect(user).toEqual({})
  })
})
Previous
Best Practice for Mock TypeORM