How to mock a TypeScript interface with Jest?

Sometimes, we want to mock a TypeScript interface with Jest.

In this article, we’ll look at how to mock a TypeScript interface with Jest.

How to mock a TypeScript interface with Jest?

To mock a TypeScript interface with Jest, we just need to create objects that match the shape of the interface.

For instance, we write

mathlib.multiplier = {
  multiply: jest.fn((a, b) => a * b),
};

to mock the multiply function with jest.fn assuming the multiply method looks like

interface IMultiplier {
  multiply(a: number, b: number): number;
}

The mocked function takes 2 numbers as arguments and returns a number, and we have the same signature and return type in the mocked function.

So no error will be raised.

Conclusion

To mock a TypeScript interface with Jest, we just need to create objects that match the shape of the interface.