Currently delving into the world of NestJS and feeling a bit perplexed about the workings of "modules". In my project, I have two modules namely JokesModule
and ChuckNorrisApiModule
. My goal is to utilize the service provided by ChukNorrisService
within the JokesService
.
Everything seems fine during compilation as no errors are thrown, but things take a turn for the worse when running the tests (generated using nest g service
and nest g module
), resulting in failure.
The breakdown of the modules:
@Module({
providers: [ChuckNorrisApiService],
imports: [HttpModule],
exports: [ChuckNorrisApiService]
})
export class ChuckNorrisApiModule {}
@Module({
providers: [JokesService],
imports: [ChuckNorrisApiModule]
})
export class JokesModule {}
And here's a glimpse at the services:
@Injectable()
export class ChuckNorrisApiService {
constructor(private httpService: HttpService) {}
}
@Injectable()
export class JokesService {
constructor(
private readonly service: ChuckNorrisApiService,
) {}
}
The test scenario:
describe('JokesService', () => {
let service: JokesService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [JokesService],
}).compile();
service = module.get<JokesService>(JokesService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Encountering an error message:
Nest cant resolve dependencies of the JokesService (?). Please make sure that the
argument ChuckNorrisApiService at index [0] is available in the RootTestModule context.
Potential solutions:
- If ChuckNorrisApiService is a provider, is it part of the current RootTestModule?
- If ChuckNorrisApiService is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing ChuckNorrisApiService */ ]
})
Puzzling over whether creating an entire module solely for utilizing ChuckNorrisApiService
in just one other service is necessary. Any insights on best practices would be highly appreciated from experienced NestJS users!
If you have any clues regarding the issue at hand or guidance on the aforementioned query, do share your wisdom! Thank you.