API reference

Mocking DataSource

DataSource

There are multiple ways we can call TypeORM. One way is to use DataSource directly. Let's see it in action.

import { Column, DataSource, Entity, PrimaryGeneratedColumn } from 'typeorm'

@Entity({ name: 'users' })
class User {
  @PrimaryGeneratedColumn('uuid')
  id: string

  @Column({ name: 'name', type: 'text', nullable: false })
  name: string
}

const dataSource = new DataSource({
  type: 'mysql',
  host: 'localhost',
  username: 'root',
  password: 'password',
  port: 3305,
  synchronize: false,
  logging: true,
  database: 'mock',
  entities: [User],
})

Now we can get the User Repository from the dataSource and call its methods, e.g., find.

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

To mock the find method, simply create a mock instance and then add mock data tied to a specific method of the User repository, e.g.,

Example

test('find()', 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'])
})

I wrap all the DataSource methods with spies so that we don’t accidentally interact with the database; otherwise, there would be no point in mocking. All these methods are covered, e.g.,

  • initialize
  • destroy
  • dropDatabase
  • runMigrations
  • showMigrations
  • synchronize
  • undoLastMigration

So, if you call these above methods, it would simply call the spy function, not the actual implementation, to avoid interacting with the database.

Previous
Handling Errors