[Jest] Jest Typescript — mocking static method

David Ting
1 min readOct 31, 2021

--

Recently, I needed to mock a static method for my unit tests using Jest with Typescript. I’ve come across a few different ways to implement it, and this is my preferred way to do it.

Example Implementation

Given a class with a static method:

And the class under test that invokes the static method:

To mock the static method, simply assign jest.fn() to the static method like so:

Another scenario is when private constructor is used to instantiate a class (see: When to use a private constructor), the question arises — how do I mock the dependencies? Here’s how:

Given a dependency class that instantiate using a static get() method:

and the subject under test:

In the unit test, the dependency can be mocked in a similar fashion by mocking the static instantiation get() method and mock return the mock object:

and now the dependency can be mocked on spied on.

References

--

--