Search⌘ K
AI Features

Creating Mock Objects

Explore how to create mock functions with Jest for React unit testing. Understand specifying return values, mocking implementations, throwing errors, and verifying function calls to build reliable tests.

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
...