如何在NestJS中对TypeORM的自定义存储库进行单元测试? [英] How to unit test a custom repository of TypeORM in NestJS?
本文介绍了如何在NestJS中对TypeORM的自定义存储库进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要测试的类
我的TypeORM存储库extends
AbstractRepository:
@EntityRepository(User)
export class UsersRepository extends AbstractRepository<User> {
async findByEmail(email: string): Promise<User> {
return await this.repository.findOne({ email })
}
}
单元测试
describe('UsersRepository', () => {
let usersRepository: UsersRepository
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersRepository]
}).compile()
usersRepository = module.get<UsersRepository>(UsersRepository)
})
describe('findByEmail', () => {
it(`should return the user when the user exists in database.`, async () => {
const fetchedUser = await usersRepository.findByEmail('test1@test.com')
})
})
})
此处,我收到错误:
TypeError: Cannot read property 'getRepository' of undefined
at UsersRepository.get (repository/AbstractRepository.ts:43:29)
at UsersRepository.findByEmail (users/users.repository.ts:11:23)
at Object.<anonymous> (users/users.repository.spec.ts:55:49)
所以,我的问题是,我如何模拟repository
或repository.findOne
?
换句话说,如何模拟AbstractRepository
继承自protected
且无法从UsersRepository
实例访问的字段?
有一个similar question here,但它是从Repository<Entity>
而不是AbstractRepository<Entity>
延伸而来的。他们能够模拟findOne
,因为它是public
。
我尝试的内容
我尝试用NestJS推荐的方式模拟它,但这是针对非自定义存储库的,在我的情况下不起作用:
{
provide: getRepositoryToken(User),
useValue: {
findOne: jest.fn().mockResolvedValue(new User())
}
}
推荐答案
我选择了内存数据库解决方案。这样,我就不必模拟TypeORM的复杂查询。单元测试在不命中实际数据库的情况下运行得同样快。
我的生产数据库是PostgreSQL,但是我可以使用SQLite内存数据库进行单元测试。这之所以可行,是因为TypeORM提供了对数据库的删减。只要我们满足存储库的接口,我们在幕后使用什么数据库并不重要。以下是我的测试结果:
const testConnection = 'testConnection'
describe('UsersRepository', () => {
let usersRepository: UsersRepository
beforeEach(async () => {
const connection = await createConnection({
type: 'sqlite',
database: ':memory:',
dropSchema: true,
entities: [User],
synchronize: true,
logging: false,
name: testConnection
})
usersRepository = connection.getCustomRepository(UsersRepository)
})
afterEach(async () => {
await getConnection(testConnection).close()
})
describe('findByEmail', () => {
it(`should return the user when the user exists in database.`, async () => {
await usersRepository.createAndSave(testUser)
const fetchedUser = await usersRepository.findByEmail(testUser.email)
expect(fetchedUser.email).toEqual(testUser.email)
})
})
})
这篇关于如何在NestJS中对TypeORM的自定义存储库进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文