I am trying to test my Nest application using jest. I am doing a very basic check of my service. like this:
import { Test, TestingModule } from "@nestjs/testing";
import { getRepositoryToken } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AuditLog } from "./audit-log.entity";
import { AuditLogService } from "./audit-log.service"
/* const mockAuditLogRepository = () => ({
find: jest.fn(),
create: jest.fn(),
save: jest.fn()
}) */
describe('AuditLogService', () => {
let service: AuditLogService;
let repo: Repository<AuditLog>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuditLogService,
{
provide: getRepositoryToken(AuditLog),
useValue: {
create: jest.fn()
}
}
],
}).compile();
service = module.get<AuditLogService>(AuditLogService)
repo = module.get<Repository<AuditLog>>(getRepositoryToken(AuditLog))
});
test("it should be defined", () => {
expect(service).toBeDefined();
expect(repo).toBeDefined();
})
})
I am just trying to check if the service is defined but it is giving me the following error : `` Nest can't resolve dependencies of the AuditLogService (?). Please make sure that the argument AuditLogRepository at index [0] is available in the RootTestModule context.
Potential solutions:
- If AuditLogRepository is a provider, is it part of the current RootTestModule?
- If AuditLogRepository is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing AuditLogRepository */ ]
})
What am i doing wrong?
CodePudding user response:
The Problem is you are not injecting the repository in your testing Module and must be doing in the service as you said you have a repository class too. Hence you need to inject that repository too here along with the service. This may help.
import { Test, TestingModule } from "@nestjs/testing";
import { AuditLogRepository } from "./audit-log.repository";
import { AuditLogService } from "./audit-log.service"
/* const mockAuditLogRepository = () => ({
find: jest.fn(),
create: jest.fn(),
save: jest.fn()
}) */
describe('AuditLogService', () => {
let service: AuditLogService;
let repo: AuditLogRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuditLogService,
AuditLogRepository,
{
provide: AuditLogRepository,
useValue: {
create: jest.fn()
}
}
],
}).compile();
service = module.get<AuditLogService>(AuditLogService)
repo = module.get<AuditLogRepository>(AuditLogRepository)
});
test("it should be defined", () => {
expect.hasAssertions();
expect(service).toBeDefined();
expect(repo).toBeDefined();
})
})