jest mock method return value in class code example
Example 1: jest mock implementation
describe("mockImplementation", () => {
test("function", () => {
const mockFn1 = jest.fn().mockImplementation(() => 42);
const mockFn2 = jest.fn(() => 42);
expect(mockFn1()).toBe(42);
expect(mockFn2()).toBe(42);
});
Example 2: jest mockclear
test("mockFn.mockClear", () => {
const mockFn = jest.fn().mockImplementation(() => 42);
const MockClass = jest.fn();
new MockClass();
expect(mockFn()).toBe(42);
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
new MockClass();
expect(mockFn()).toBe(42);
expect(mockFn.mock.calls).toHaveLength(2);
expect(MockClass.mock.instances).toHaveLength(2);
mockFn.mockClear();
MockClass.mockClear();
new MockClass();
expect(mockFn()).toBe(42);
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
});