I encountered an issue where I am unable to access the repository in my test. It appears that the repository is not being injected during the test. Below is the code snippet I used:
ads.module.ts
@Module({
imports: [
TypeOrmModule.forFeature([Ads]),
ProfilesModule,
],
providers: [AdsService],
controllers: [AdsController],
exports: [AdsService],
})
export class AdsModule {}
profile.module.ts
@Module({
imports: [
TypeOrmModule.forFeature([Profiles]),
],
providers: [ProfilesService],
controllers: [ProfilesController],
exports: [ProfilesService],
})
export class ProfilesModule {}
ads.service.ts
@Injectable()
export class AdsService {
constructor(
@InjectRepository(Ads) private adsRepository: Repository<Ads>,
private profileService: ProfilesService,
) {}
create = async (createAdsDto: AdsDto) => {
const profile = await this.profileService.findByProfileId(
createAdsDto.profileId,
);
return null;
}
}
profiles.service.ts
@Injectable()
export class ProfilesService {
constructor(
@InjectRepository(Profiles) private profileRepository: Repository<Profiles>
) {}
findByProfileId = async (id: number): Promise<Profiles> => {
// below line is failing
const profile = await this.profileRepository.findOne({
where: { id },
relations: { user: true, avatar: true },
});
return profile;
};
}
ads.service.spec.ts
describe('AdsService', () => {
let service: AdsService;
let adsRepository: Repository<Ads>;
let profileRepository: Repository<Profiles>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AdsService,
{
provide: getRepositoryToken(Ads),
useClass: Repository
},
ProfilesService,
{
provide: getRepositoryToken(Profiles),
useClass: Repository
},
],
}).compile();
service = module.get(AdsService);
adsRepository = module.get<Repository<Ads>>(getRepositoryToken(Ads));
profileRepository = module.get<Repository<Profiles>>(
getRepositoryToken(Profiles),
);
});
afterAll(() => {
jest.resetAllMocks();
});
describe('Initial variables must be defined', () => {
test('Ads Service must be defined', () => {
expect(service).toBeDefined();
});
test('Ads Repository must be defined', () => {
expect(adsRepository).toBeDefined();
});
test('Profile Repository must be defined', () => {
expect(profileRepository).toBeDefined();
});
test('can create ads', async () => {
const ads = await service.create({
profileId: 1,
type: 'Oferta',
category: 'Vivienda',
location: 'Alicante',
title: 'Apartment For Rent',
description: 'This is a sample description',
extract: 'This is a sample extract short description',
} as AdsDto);
});
});
});
The failure seems to be related to the profile service's inability to inject the repository during the test. Here is a screenshot of the test result: