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

标签 testing static jasmine spy

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

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

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

如何测试在调用 normalFunction() 时是否调用了静态函数?

最佳答案

您可以像这样设置一个简单的 spy (正如您已经从问题中的标签猜到的那样):

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。

关于testing - Jasmine:在另一个类中测试静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54175618/

相关文章:

php - 测试调用静态方法的 PHP 代码

java - Java中如何使用内部静态变量?

angular - 不能等到 DOM 渲染在 Angular/Jasmine 单元测试中完成

reactjs - 使用与 typescript react 的 Jest 测试复制到剪贴板方法

php - Laravel 5.0 用户 Eloquent 模型 mock

c++ - C++中类的静态数据成员和静态方法是静态对象吗?

angularjs - 使用模拟测试 AngularJS 服务的初始化

javascript - Angular 单元测试服务返回 Promise Jasmine

Python 故障注入(inject)

ruby-on-rails - 如何 catch Rails 站点的测试