I am currently writing unit tests using the Vitest framework for my TypeScript and React application, but I have encountered an issue with mocking static methods.
Below is a snippet of my code:
export class Person {
private age: number;
constructor(public name: string) {
this.age = 20;
}
public getAge() {
return this.age;
}
}
export class StaticPerson {
public static getAge() {
return 20;
}
}
import { Person, StaticPerson } from "./person";
export class Interviewer {
public askAge(): number {
const person = new Person("John");
return person.getAge();
}
public askStaticAge(): number {
return StaticPerson.getAge();
}
}
Unit tests:
import { describe, it, expect, vi } from "vitest";
import { Interviewer } from "./interviewer";
// Test that passes
describe("interviewer", () => {
it("return mocked age", () => {
vi.mock("./person", () => {
const Person = vi.fn(() => ({
getAge: vi.fn(() => 15),
}));
return { Person };
});
const interviewer = new Interviewer();
const age: number = interviewer.askAge();
expect(age).toBe(15);
});
});
// This test fails
it("return mocked age from static method", () => {
vi.mock("./person", () => {
const StaticPerson = vi.fn(() => ({
getAge: vi.fn(() => 15),
}));
return { StaticPerson };
});
const interviewer = new Interviewer();
const age: number = interviewer.askStaticAge();
expect(age).toBe(15);
});
The first test, where I call the non-static method, works correctly. However, the second test, where I call the static getAge method, throws an error:
TypeError: StaticPerson.getAge is not a function
FAIL src/interviewer.test.tsx > return mocked age from static method TypeError: StaticPerson.getAge is not a function ❯ Interviewer.askStaticAge src/interviewer.tsx:10:25 8| 9| public askStaticAge(): number { 10| return StaticPerson.getAge(); | ^ 11| } 12| } ❯ src/interviewer.test.tsx:29:35
I have searched the documentation but cannot find any information on mocking static methods or examples of how to do so.