Nest.js无法解决对TestingModule的循环依赖

Nic*_*Kao 3 backend typescript nestjs

我已经为 Nest 应用程序构建了一个新的模块和服务,它具有循环依赖关系,当我运行应用程序时,它会成功解析,但是当我运行测试时,我的模拟模块(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(){...}
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试文件时,我得到:

“Nest 无法解析 MathService 的依赖关系(...)。请确保索引 [x] 处的参数依赖关系在 RootTestModule 上下文中可用。”

我尝试从“LimitsService”中注释掉“mathService”,当我这样做时它会起作用,但我需要 mathService。

我还尝试导入“LimitsModule”,而不是使用forwardRef() 提供“LimitsService”,然后从mockModule 获取“LimitsService”,但这引发了相同的错误。

将我的“LimitsService”导入模拟模块的正确方法是什么?

Nic*_*Kao 8

这现在对我有用。

解决方案

导入 LimitsService 的 jest 模拟

jest.mock('@Limits/limits.service');
Run Code Online (Sandbox Code Playgroud)

使用模拟设置 Provider

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);
    
 });
Run Code Online (Sandbox Code Playgroud)