I want to unit-test a class which getCustomRepository in it's constructor but I just can't figure an easy way to mock it. Here is my class code
import {getCustomRepository} from 'typeorm';
export class Controller {
private repository: UserRepository;
constructor() {
this.repository = getCustomRepository(UserRepository); //I want to mock this.
}
async init() {
return this.repository.findUser(1);
}
}
and here are tests
describe('User Tests', () => {
it('should return user', async () => {
//Fake user to be resolved.
const user = new User();
user.id = 2;
//I want to mock getCustomRepository(UserRepository); here
//getCustomRepository = jest.fn().mockResolvedValue(UserRepository); HERE HOW???
//Mocking find user
UserRepository.prototype.findUser = jest.fn().mockResolvedValue(user);
const controller = new Controller();
const result = await controller.init();
expect(result).toBeDefined();
});
});
Note: Mocking repository methods works well but I really want to mock getCustomRepository so as It may reduce time which is wasted trying to connect to database.
This is how getCustomRepository in typeORM looks like
export declare function getCustomRepository<T>(customRepository: ObjectType<T>, connectionName?: string): T;
UserRepository.ts
@EntityRepository(User)
export class UserRepository extends Repository<User> {
public async findUser(id: number) {
return 'real user';
}
}
User.ts
@Entity('users')
export class User{
@PrimaryGeneratedColumn()
id: number;
@Column({type: 'varchar', length: 100})
name: string;
}
So question is how do I mock it? Any help will be much appreciated.
Controller
class, how does thegetCustomRepository
get imported? Can you add that part to your question? – mgarciaimport {getCustomRepository} from 'typeorm';
– Nux