Is it possible to mock a typescript interface with jest?
For example:
import { IMultiplier } from "./IMultiplier";
export class Math {
multiplier: IMultiplier;
public multiply (a: number, b: number) {
return this.multiplier.multiply(a, b);
}
}
Then in a test:
import { Math } from "../src/Math";
import { IMultiplier } from "../src/IMultiplier";
describe("Math", () => {
it("can multiply", () => {
let mathlib = new Math();
mathlib.multiplier = // <--- assign this property a mock
let result = mathlib.multiply(10, 2);
expect(result).toEqual(20);
});
});
I've tried to create a mock object to satisfy this a number of ways, but none work. For example assigning it this mock:
let multiplierMock = jest.fn(() => ({ multiply: jest.fn() }));
Will produce something along the lines of:
Error - Type 'Mock<{ multiply: Mock<{}>; }>' is not assignable to type 'IMultiplier'.
multiplier
get created/assigned within an instance ofMath
? – Coinsure{} as MyInterface
) and then just add mocks for the properties/methods needed for testing - https://mcmap.net/q/330712/-mocking-stubbing-a-typescript-interface-with-jest – Peppery