Search code examples
javascriptclassstaticjasminespy

How to spyOn a static class method with Jasmine


I have a class with a static method that I want to test in Jasmine. I understand that static methods are not callable on instances of the class. So besides the fact that it cannot find the method to spyOn, my test does not pass, but how would one go about testing static methods in a class with Jasmine?

class Foo {
    static foobar (a, b) {
      return a * b
    }
}

Jasmine Test

it ('should test a static method', () => {
    let foo = new Foo()
    spyOn(foo, 'foobar')
    foo.foobar(2,3)
    expect(foo.foobar).toBe(6)
})

Solution

  • You should be able to use spyOn(Foo, 'foobar') to make it a spy.

    Also spies are not intended to directly be tested - they are a tool so that you can test other code more deterministically and in isolation.