如何在 Nestjs/TypeORM 应用程序中测试自定义 Repository [英] How to test custom Repository in Nestjs/TypeORM applications
问题描述
我正在尝试添加更多测试代码以提高示例代码的质量.
I am trying to add more testing codes to improve the quality of my sample codes.
目前,我在测试 UserRepository
时遇到问题(不是模拟 UserRepository),我在自定义 UserRepository
中添加了一些自定义方法像这样.
Currently, I have a problem when testing UserRepository
(not mock UserRepository), there are some custom methods I added in my custom UserRepository
like this.
@EntityRepository(UserEntity)
export class UserRepository extends Repository<UserEntity> {
findByEmail(email: string): Promise<UserEntity> {
return this.findOne({ email: email });
}
}
所以我想验证 findOne
是从父 Repository
调用的.
So I want to verify the findOne
is called from the parent Repository
.
我尝试添加以下测试代码.
I tried to add the following testing codes.
describe('UserRepository', () => {
let local;
let parentMock;
beforeEach(() => {
local = Object.getPrototypeOf(UserRepository);
parentMock = {
new: jest.fn(),
construtor: jest.fn(),
findOne: jest.fn(),
};
Object.setPrototypeOf(UserRepository, parentMock);
});
afterEach(() => {
Object.setPrototypeOf(UserRepository, local);
});
it('should call findOne', async () => {
const findByEmailSpy = jest.spyOn(parentMock, 'findOne');
const users = new UserRepository();
await users.findByEmail('test@example.com');
expect(parentMock.mock.calls.length).toBe(1);
expect(findByEmailSpy).toBeCalledWith({
email: 'test@example.com',
});
});
});
运行测试时,它抱怨 new UserRepository()
没有构造函数().
When running the tests, it complains there is no constructor() for new UserRepository()
.
有没有办法解决这个问题,或者有更好的方法来编写这些测试代码?
Is there any way to fix this issue, or a better way to write these testing codes?
推荐答案
为了正确测试用户存储库,必须模拟 Repository.prototype.findOne
.
In order to properly test the user repository, Repository.prototype.findOne
has to be mocked.
import { Test, TestingModule } from '@nestjs/testing';
import { Repository } from 'typeorm';
import { UserRepository } from './user.repository';
describe('UserRepository', () => {
let userRepository: UserRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserRepository],
}).compile();
userRepository = module.get<UserRepository>(UserRepository);
});
describe('findByEmail', () => {
it('should return found user', async () => {
const email = 'email';
const user = {
email,
};
const findOneSpy = jest
.spyOn(Repository.prototype, 'findOne')
.mockResolvedValue(user);
const foundUser = await userRepository.findByEmail(email);
expect(foundUser).toEqual(user);
expect(findOneSpy).toHaveBeenCalledWith(user);
});
});
});
这篇关于如何在 Nestjs/TypeORM 应用程序中测试自定义 Repository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!