我为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
但是当我运行测试文件时,我得到了:
“嵌套无法解析MathService的依赖项(...)。请确保在RootTestModule上下文中索引[x]处的参数依赖项可用。”
我尝试从“ LimitsService”中注释掉“ mathService”,当我这样做时它可以工作,但是我需要mathService。
我也尝试过导入“ LimitsModule”而不是为forwardRef()提供“ LimitsService”,然后从模拟模块中获取“ LimitsService”,但这会引发相同的错误。
将“ LimitsService”导入到模拟模块中的正确方法是什么?
答案 0 :(得分:0)
这现在对我有用。
导入LimitsService的玩笑
jest.mock('@Limits/limits.service');
使用模拟设置提供商
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);
});