【发布时间】:2020-12-29 11:40:53
【问题描述】:
我为 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 的正确方法是什么?
【问题讨论】:
-
看来LimitsService需要两个依赖,即ListService和MathService。但是,在您的代码中,您没有提供 ListService 作为提供者。也许您可以将 ListService 添加到您的提供商列表中,然后再试一次。
-
我添加示例时的错误,在我的代码中,我确实将 ListService 列为提供者
标签: typescript backend nestjs