jest function code example
Example 1: jest mock reset
test("mockFn.mockReset", () => {
const mockFn = jest.fn().mockImplementation(() => 43);
const MockClass = jest.fn();
new MockClass();
expect(mockFn()).toBe(43);
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
mockFn.mockReset();
MockClass.mockReset();
new MockClass();
expect(mockFn()).toBeUndefined();
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
});
Example 2: 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 3: jest mock call
test("mock.calls", () => {
const mockFn = jest.fn();
mockFn(1, 2);
expect(mockFn.mock.calls).toEqual([[1, 2]]);
});
Example 4: jest mock mockname
test("mockName", () => {
const mockFn = jest.fn().mockName("mockedFunction");
mockFn();
expect(mockFn).toHaveBeenCalled();
});