Testing · Senior · Question 63 of 75
How do you mock a class constructor with Vitest/Jest?
vi.mock("./Logger", () => ({
Logger: vi.fn().mockImplementation(() => ({ log: vi.fn() })),
}));- ✓Correct answer: Mock the module and return a mock constructor whose instances have mocked methods
- 2Use
vi.spyOn(Logger)without a method name - 3Classes can't be mocked
Explanation
Logger.mock.instances / mock.results give access to the created instances.