茉莉花:在另一个类中测试静态函数

时间:2019-01-14 03:58:45

标签: testing static jasmine spy

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

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

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

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

1 个答案:

答案 0 :(得分: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是实现上述测试并通过的堆叠闪电战。