Mock a typescript interface with jest
try out moq.ts library.
import {Mock} from "moq.ts";
const multiplier = new Mock<IMultiplier>()
.setup(instance => instance.multiply(3, 4))
.returns(12)
.object();
let mathlib = new Math();
mathlib.multiplier = multiplier;
The mock just needs to have the same shape as the interface.
(from the docs: One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”.)
So mathlib.multiplier
just needs to be assigned to an object that conforms to IMultiplier
.
I'm guessing that IMultiplier
from the example looks something like this:
interface IMultiplier {
multiply(a: number, b: number): number
}
So the example test will work fine by changing the line in question to this:
mathlib.multiplier = {
multiply: jest.fn((a, b) => a * b)
};
I created a library which allows you to mock out TypeScript interfaces - https://github.com/marchaos/jest-mock-extended.
There didn't seem to be libs that does this cleanly whilst keeping full type safety. It's based loosely on the discussion here -https://github.com/facebook/jest/issues/7832