1

Assuming i have a static class and a normal class as below.

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

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

How do I test that the static function is called when normalFunction() is called?

Fabian Küng
  • 5,925
  • 28
  • 40
Tan Vee Han
  • 65
  • 2
  • 9

1 Answers1

3

You can set up a simple spy (as you already guessed by the tag from your question) like this:

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 is a stackblitz that has the above test implemented and passing.

Fabian Küng
  • 5,925
  • 28
  • 40