Jasmine:在另一个类中测试静态函数

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

假设我有一个静态类和一个普通类,如下所示。

class StaticClass {
  static staticFunction() { 
    console.log('Static function called.');
  }
}

class NormalClass {
  normalFunction() { 
    StaticCLass.staticFunction();
  }
}

当调用normalFunction()时,如何测试静态函数?

testing static jasmine spy
1个回答
1
投票

您可以设置一个简单的间谍(正如您已经从问题中的标记中猜到的),如下所示:

it('should test if the static function is being called ', () => {
  // Set up the spy on the static function in the StaticClass
  let spy = spyOn(StaticClass, 'staticFunction').and.callThrough();
  expect(spy).not.toHaveBeenCalled();

  // Trigger your function call
  component.normalFunction();

  // Verify the staticFunction has been called
  expect(spy).toHaveBeenCalled();
  expect(spy).toHaveBeenCalledTimes(1);
});

Here是一个stackblitz,它已经实现并通过了上述测试。

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