Reputation: 331
I am stuck with the dependency injection problem of NestJS during the unit test with jest. Here is my codebase. app.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
The problem is, there is dependency injection in app.service.ts
import { Injectable, CACHE_MANAGER, Inject } from "@nestjs/common";
import {Cache} from "cache-manager";
@Injectable()
export class AppService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
getHello(): string {
return "Hello World!";
}
}
In general, nest automatically performs dependency injection during bootup, but this isn't happening while running unit-test and giving me the following error:
Nest can't resolve dependencies of the AppService (?). Please make sure that the argument CACHE_MANAGER at index [0] is available in the RootTestModule context.
Any idea how can I resolve this issue?
Upvotes: 2
Views: 4782
Reputation: 502
You need to add the CACHE_MANAGER
as a provider to your TestingModule:
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [
AppService,
{ provide: CACHE_MANAGER, useFactory: jest.fn() },
],
}).compile();
Upvotes: 11