Reputation: 333
I have built a new module and service for a Nest app, it has a circular dependency that resolves successfully when I run the application, but when I run the tests, my mockedModule (TestingModule) can't resolve the dependency for the new service I created.
Example of the "LimitsService" created with a circular dependency with "MathService":
@Injectable()
export class LimitsService {
constructor(
private readonly listService: ListService,
@Inject(forwardRef(() => MathService))
private readonly mathService: MathService,
) {}
async verifyLimit(
user: User,
listId: string,
): Promise<void> {
...
this.mathService.doSomething()
}
async someOtherMethod(){...}
}
MathService calls LimitService.someOtherMethod in one of its methods.
This is how the testing module for "MathService" is setup (everything worked fine before without "LimitsService"):
const limitsServiceMock = {
verifyLimit: jest.fn(),
someOtherMethod: jest.fn()
};
const listServiceMock = {
verifyLimit: jest.fn(),
someOtherMethod: jest.fn()
};
describe('Math Service', () => {
let mathService: MathService;
let limitsService: LimitsService;
let listService: ListService;
let httpService: HttpService;
beforeEach(async () => {
const mockModule: TestingModule = await Test.createTestingModule({
imports: [HttpModule],
providers: [
MathService,
ConfigService,
{
provide: LimitsService,
useValue: limitsServiceMock
},
{
provide: ListService,
useValue: listServiceMock
},
],
}).compile();
httpService = mockModule.get(HttpService);
limitsService = mockModule.get(LimitsService);
listService = mockModule.get(ListService);
mathService= mockModule.get(MathService);
});
...tests
But when I run the test file, I get:
"Nest can't resolve dependencies of the MathService (...). Please make sure that the argument dependency at index [x] is available in the RootTestModule context."
I have tried commenting out "mathService" from "LimitsService" and it works when I do that,but I need mathService.
I have also tried importing "LimitsModule" instead of providing "LimitsService" with forwardRef() and then getting "LimitsService" from mockModule but that threw the same error.
What is the proper way of importing my "LimitsService" into the mockModule?
Upvotes: 5
Views: 6522
Reputation: 333
This is now working for me.
Import jest mock of LimitsService
jest.mock('@Limits/limits.service');
Set Provider with mock
describe('Math Service', () => {
let mockLimitsService : LimitsService;
let mathService: MathService;
let listService: ListService;
let httpService: HttpService;
beforeEach(async () => {
const mockModule: TestingModule = await Test.createTestingModule({
imports: [HttpModule],
providers: [
MathService,
ConfigService,
LimitsService,
{
provide: ListService,
useValue: listServiceMock
},
],
}).compile();
mockLimitsService = mockModule.get(LimitsService);
httpService = mockModule.get(HttpService);
listService = mockModule.get(ListService);
mathService= mockModule.get(MathService);
});
Upvotes: 14