homeresume
 
   

Testing custom repositories (NestJS/TypeORM)

September 5, 2021

Custom repositories extend base repository class and enrich it with several additional methods.

// user.repository.ts
@Injectable()
@EntityRepository(UserEntity)
export class UserRepository extends Repository<UserEntity> {
async getById(id: string): Promise<User> {
return this.findOne({ id });
}
// ...
}

Custom repository can be injected into the service using the InjectRepository decorator.

export class UserService {
constructor(
@InjectRepository(UserRepository)
private readonly userRepository: UserRepository,
) {}
async getById(id: string): Promise<User> {
return this.userRepository.getById(id);
}
// ...
}

Instantiation responsibility can be delegated to Nest by passing repository class to the forFeature method.

@Module({
imports: [
TypeOrmModule.forFeature([UserRepository]),
// ...
],
providers: [UserService],
// ...
})
export class UserModule {}

In order to properly test the custom repository, some of the methods has to be mocked.

describe('UserRepository', () => {
let userRepository: UserRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserRepository],
}).compile();
userRepository = module.get<UserRepository>(UserRepository);
});
describe('getById', () => {
it('should return found user', async () => {
const id = 'id';
const user = {
id,
};
const findOneSpy = jest
.spyOn(userRepository, 'findOne')
.mockResolvedValue(user as UserEntity);
const foundUser = await userRepository.getById(id);
expect(foundUser).toEqual(user);
expect(findOneSpy).toHaveBeenCalledWith(user);
});
});
});

 

© 2021