Understanding Mocking

Learn about mock and its uses in a test in this lesson.

What is a mock?

A mock is a type of test double. A test double is a replacement for part of a codebase to make testing easier. For instance, web API calls are often mocked. This is useful for a few reasons:

  • To ensure the web API call response is consistent. The data behind the real web API will probably change over time, causing the real web API response to vary.

  • To speed up the test. Web API requests are slow.

  • To reduce costs if the web API is a third-party paid service.

Mock vs. stub

Another type of test double is a stub. Stubs are prewritten alternative implementations for part of the code. In the example below, FakeApi is a stub that we have fully implemented:

const api = new FakeApi();
const component = new Component(api);
component.render();
expect(component).toContain("some stuff");

The FakeApi function is an alternative implementation to the real Api.

Note: The example code above isn’t React or Jest. Hopefully, it helps you understand what a stub is.

A mock is slightly different than a stub. A mock consists of prewritten expectations for an alternative implementation part of code. In the example below, mock wraps the real Api and allows us to define the return value via a returns method:

const api = mock(Api);
api.returns("some stuff");
const component = new Component(api);
component.render();
expect(component).toContain("some stuff");

Again, the example code above isn’t React or Jest.

Mocks are usually preferred to stubs because they don’t cost as much to create or maintain.

Mocks and stubs are often confused since the Jest API and documentation don’t make a clear distinction. In response, we’ll refer to both mocks and stubs as “mocks” for the remainder of this course.

Get hands-on with 1200+ tech skills courses.