Skip to content

Mocking

Wei edited this page Mar 21, 2019 · 1 revision

Mocking is a technique to isolate test subjects by replacing dependencies with objects that you can control and inspect.

The goal for mocking is to replace something we don’t control with something we do test("returns undefined by default", () => { const mock = jest.fn();

let result = mock("foo");

expect(result).toBeUndefined(); expect(mock).toHaveBeenCalled(); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith("foo"); });

Testing Foreach using Mock Functions

function forEach(items, callback) { for (let index = 0; index < items.length; index++) { callback(items[index]); } }

const mockCallback = jest.fn(x => 42 + x); forEach([0, 1], mockCallback);

// The mock function is called twice expect(mockCallback.mock.calls.length).toBe(2);

// The first argument of the first call to the function was 0 expect(mockCallback.mock.calls[0][0]).toBe(0);

// The first argument of the second call to the function was 1 expect(mockCallback.mock.calls[1][0]).toBe(1);

// The return value of the first call to the function was 42 expect(mockCallback.mock.results[0].value).toBe(42);

Clone this wiki locally