我为 Nest 应用程序构建了一个新模块和服务,它有一个循环依赖关系,当我运行应用程序时成功解析,但是当我运行测试时,我的 mockedModule (TestingModule) 无法解析新服务的依赖关系我创建的。
使用“MathService”循环依赖创建的“LimitsService”示例:
@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 在其方法之一中调用 LimitService.someOtherMethod。
这就是“MathService”测试模块的设置方式(在没有“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
但是当我运行测试文件时,我得到:
“Nest 无法解析 MathService (...) 的依赖关系。请确保索引 [x] 处的参数依赖关系在 RootTestModule 上下文中可用。”
我尝试从“LimitsService”中注释掉“mathService”,当我这样做时它可以工作,但我需要 mathService。
我也尝试过导入“LimitsModule”,而不是使用 forwardRef() 提供“LimitsService”,然后从 mockModule 获取“LimitsService”,但这会引发同样的错误。
将我的“LimitsService”导入 mockModule 的正确方法是什么?