API reference
JavaScript Guide
As you know, TypeORM also supports JavaScript. However, we need to follow a slightly different approach to create a Repository because we cannot use TypeScript-like decorators in JavaScript. So we need to use EntitySchema
for that. Here’s how you can do this:
Create a Repository
import { EntitySchema } from 'typeorm'
const User = new EntitySchema({ name: 'User', tableName: 'users', columns: [] })
Mock EntitySchema methods
To mock User methods, e.g., find
, here’s how you can do it:
it('test', async () => {
const mockUsers = ['user']
const typeorm = new MockTypeORM()
typeorm.onMock('User').toReturn(mockUsers, 'find')
const users = await dataSource.getRepository(User).find()
expect(users).toEqual(mockUsers)
})
Important Note
In the onMock
method, when we are using JavaScript, we always provide the Repository name as a string, and it should match the object name of the EntitySchema
, e.g., we just created the User
object before:
const User = new EntitySchema({ ... });
So you must provide "User" in the onMock
function argument. If the object name is different, e.g.,
const UserEntity = new EntitySchema({ ... });
then you need to provide "UserEntity" in the onMock function argument. Here’s the test case for that:
it('test', async () => {
const mockUsers = ['user']
const typeorm = new MockTypeORM()
typeorm.onMock('UserEntity').toReturn(mockUsers, 'find')
const users = await dataSource.getRepository(UserEntity).find()
expect(users).toEqual(mockUsers)
})
Everything else remains the same as we are doing with TypeScript. The only change is that when calling the onMock
function, we need to provide the Repository name as a string.