Nest can't resolve dependencies of the JokesService (?)

I am learning NestJS and I a bit confused of how this "modules" work. I only have two modules, JokesModule and ChuckNorrisApiModule, and I am trying to use the service of ChukNorrisService in JokesService. I am already exporting the ChuckNorrisService and importing ChuckNorrisModule into the JokesModule.

It runs good, the compiler does't throw any errors, but when I run the tests (which comes with the nest g service and nest g module), it fails.

The modules:

@Module({
  providers: [ChuckNorrisApiService],
  imports: [HttpModule],
  exports: [ChuckNorrisApiService]
})
export class ChuckNorrisApiModule {}
@Module({
  providers: [JokesService],
  imports: [ChuckNorrisApiModule]
})
export class JokesModule {}

And the services:

@Injectable()
export class ChuckNorrisApiService {
    constructor(private httpService: HttpService) {}
}
@Injectable()
export class JokesService {
  constructor(
    private readonly service: ChuckNorrisApiService,
  ) {}
}

The test:

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();
  });
});

And the error:

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 */ ]
      })

Just a question for the pros in NestJS, if I only want to use the ChuckNorrisApiService in just one other service, do I to create an entire module for that? What are the best practices for this?

If someone has any idea why this happens or the answer to the question above, please let me know! Thank You.

Upvotes: 1

Views: 2865

Answers (1)

Juanjo
Juanjo

Reputation: 734

You need to import the required module in the RootTestModule plus mock the dependencies if you are unit testing.

Upvotes: 0

Related Questions