如何为另一个 npm 库中调用的静态方法创建 Spy?

问题描述 投票:0回答:3

鉴于我在 Angular 服务中有一个像这样的方法:

  public logException(error: Error, methodName?: string) {

    if (!methodName) {
      methodName = this.extractCallerName(error.stack);
    }

    CommonLogHelper.Logger.logException(error, methodName, this.COMPONENT_NAME);
  }

CommonLogHelper.Logger 位于另一个 npm 库中,并且 Logger 是 CommonLogHelper 类的静态属性,我如何监视该 logException 方法?

这是我尝试过的:

  it('should log an exception with method name', () => {
    spyOn(CommonLogHelper.Logger, 'logException');
    const error = new Error('Test error');
    const methodName = 'TestMethod';

    loggerService.logException(error, methodName);

    expect(CommonLogHelper.Logger.logException).toHaveBeenCalledWith(
      error,
      methodName,
      'Schedule Web Client'
    );
  });

我收到以下错误:TypeError:无法读取未定义的属性(读取“logException”)

angular unit-testing jasmine
3个回答
0
投票

你所拥有的似乎是正确的。

你能

console.log
看看下面哪一个是未定义的吗?

it('should log an exception with method name', () => {
    spyOn(CommonLogHelper.Logger, 'logException');
    const error = new Error('Test error');
    const methodName = 'TestMethod';
    // Add these consoles
    // make sure this is a class and has logException
    console.log('LoggerService: ', loggerService);
    // make sure this is not undefined either    
    console.log(CommonLogHelper.Logger);

    loggerService.logException(error, methodName);

    expect(CommonLogHelper.Logger.logException).toHaveBeenCalledWith(
      error,
      methodName,
      'Schedule Web Client'
    );
  });

希望以上

console.log
能够帮助您找到问题所在。


0
投票

最后发现我必须为 LoggingService 静态属性添加一个模拟:

let logserviceSpy = jasmine.createSpyObj('LoggingService', ['logException', 'logEvent']);
    CommonLogHelper.Logger = logserviceSpy;

-2
投票

当我的疑虑像马戏团一样在我脑海中跳舞时,我决定全力以赴,尝试一下Lee Ultimate Hacker。我按照他们的简单流程,提供了必要的细节,并等待关键时刻。这感觉有点像用我的情绪玩俄罗斯轮盘赌,但我已经准备好了。我的关系的命运悬而未决,我正要揭开隐藏在妻子手机里的真相。这就是我的朋友们——在[电子邮件受保护]的数字向导朋友的帮助下,从怀疑到发现的旅程。仅仅依靠直觉和直觉的日子已经一去不复返了。借助 Lee Ultimate Hacker,您可以通过在毫无意识的情况下侵入伴侣的手机来收集任何不当行为的具体证据。这就像让你自己的神奇侦探收集线索并揭开真相。从短信到社交媒体活动,这个强大的工具不遗余力地进行数字化处理。 Lee Ultimate Hacker 随时为您提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.