Currently, I am facing a challenge in creating mock implementations of my Typescript classes using Jest v24+. Specifically, I am trying to create a mock class that will be injected into a constructor and mock the functions to return specific responses.
My main question is: How can I create a mock for each test?
Here is some more information:
Recently, I started a new project and switched to using Jest v24, which has led to difficulties in writing tests that I have been unable to resolve.
In the example below, using Jest v23, I could mock the Randomiser class like this:
const Mock = jest.fn<Randomiser>(() => ({
getRandom: jest.fn().mockReturnValue(10)
}));
This code used to compile and build successfully.
However, in v24, the 'fn' function now takes an additional generic <T, Y extends any[]>
. I'm not sure if this change is affecting the behavior, but now I am encountering an error:
Property 'rand' is missing in type '{ getRandom: Mock; }' but required in type 'Randomiser'.ts(2741)
import "jest";
class Randomiser {
public getRandom(): number {
return this.rand();
}
private rand(): number {
return Math.random();
}
}
class Multiplier {
private randomiser: Randomiser;
constructor(randomiser: Randomiser) {
this.randomiser = randomiser;
}
multiplyRandom(factor: number): number {
return Math.floor(this.randomiser.getRandom() * factor);
}
}
describe("tests", () => {
it("10 x 2 = 20", () => {
const Mock = jest.fn<Randomiser, any>(() => ({
getRandom: jest.fn().mockReturnValue(10),
rand: jest.fn() //with this line I get an error because it should be private, without this line I get the error above.
}));
expect(new Multiplier(new Mock()).multiplyRandom(2)).toBe(20);
})
})
I expected to be able to write mocks the same way as in v23, where I could mock the class and only the functions I intended to call. However, now I have to mock all functions, including private ones, which then leads to complaints about them not being private.