I am trying to add more testing codes to improve the quality of my sample codes.
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 });
}
}
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',
});
});
});
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?