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();
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"); });
expect(result).toBeUndefined();
expect(mock).toHaveBeenCalled();
expect(mock).toHaveBeenCalledTimes(1);
expect(mock).toHaveBeenCalledWith("foo");
});
function forEach(items, callback) { for (let index = 0; index < items.length; index++) { callback(items[index]); } }
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);
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 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 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 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);
// The return value of the first call to the function was 42
expect(mockCallback.mock.results[0].value).toBe(42);
There was an error while loading. Please reload this page.