【问题标题】:How to Mock private method in Class?如何在类中模拟私有方法?
【发布时间】:2020-01-01 11:11:19
【问题描述】:

在 Nestjs 中,我想模拟一个服务私有方法。开玩笑地说,使用spyOn 方法,我无法访问私有方法。这种情况下怎么办?

operation.service.ts

private async _getOperationDocument(id): Promise<OperationDocument> {
  return await this.operationDocumentService.findById(id);
}

operation.service.spec.ts

jest
  .spyOn(service, '_getOperationDocument')
  .mockImplementation(async id => {
    return OperationDocumentMock as OperationDocument;
  });

【问题讨论】:

    标签: unit-testing jestjs nestjs


    【解决方案1】:

    我的两件事。

    1. 您有一个单行方法,它只是调用另一个方法。我想说你根本不需要这种方法,你在添加无用的层,使代码复杂化,根本没有任何好处。

    2. 即使您最终保留了它,也没有必要嘲笑它。您不妨模拟它正在调用的方法。

    【讨论】:

    • 1.该方法还有其他逻辑。我为这个问题简化了它。 2.你说得对,我嘲笑的是被调用的服务。谢谢!
    【解决方案2】:

    感谢@Andrei-Dragotoniu,我最终改为模拟该服务。

    const module: TestingModule = await Test.createTestingModule({
      providers: [{
       provide: OperationDocumentService,
       useValue: {
         findById: () => OperationDocumentMock,
       },
     }]
    });
    

    私有方法已在另一个测试方法中调用。

    【讨论】:

    • 如果它解决了您的问题,您能否将答案标记为已接受:) 提前致谢
    • 因为这是我自己的答案,所以我必须等到明天才能这样做;)(但我会的)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多