我正在嘗試使用 jest 測驗我的 Nest 應用程式。我正在對我的服務進行非常基本的檢查。像這樣:
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();
})
})
我只是想檢查服務是否已定義,但它給了我以下錯誤:``Nest 無法決議 AuditLogService (?) 的依賴項。請確保索引 [0] 處的引數 AuditLogRepository 在 RootTestModule 背景關系中可用。
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 */ ]
})
我究竟做錯了什么?
uj5u.com熱心網友回復:
問題是您沒有在測驗模塊中注入存盤庫,并且必須按照您所說的那樣在服務中執行存盤庫類。因此,您也需要在此處與服務一起注入該存盤庫。這可能會有所幫助。
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();
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437522.html
