Creating Mock Objects

Learn to create mock functions and objects. You will also learn to specify their side effects and return values.

Mock functions

As you probably remember from earlier, you can create a mock function like this:

const mockFn = jest.fn();

You can specify its return values like:

mockFn.mockReturnValueOnce(42);

This line will make mockFn return 42 when called. However, it will only work once. To make it return 42 always, write:

mockFn.mockReturnValue(42);

If the scenario is more complicated, you may want to return different values on every function invocation. To do this, you can chain mockReturnValueOnce calls:

mockFn
  .mockReturnValueOnce(1)
  .mockReturnValueOnce('two')
  .mockReturnValueOnce(3);

console.log(mockFn()); // 1
console.log(mockFn()); // 'two'
console.log(mockFn()); // 3
...