What is Mocking and Why do we Need it?

Revisit mocking but in greater depth. Learn what it is exactly and what cases call for it.

We'll cover the following

What is mocking?

Even though we have already worked with mocking quite a bit, we barely touched the surface of this extensive topic.

Mocking is the process of substitution of software modules by the modules with the same interface. Most importantly, the mocked modules must not have any side effects (i.e., talking to the web service, interacting with the file system, or OS, etc.). We resort to mocking when it is impossible to decouple such low-level actions from logic as well as to validate the arguments and return values when working with such low-level functions.

Mocking comes in two flavours:

  • Spying: The function calls still go to the target module, but Jest remembers the calls and arguments, in order to verify them later. For example, you can verify that the webpage stores the correct cookies in the browser. There is no harm in doing that every test run.
  • MockingL The function calls do not go to the target module, and instead, you have to provide the return value for every call which requires a return value. This approach is used when you do not want certain side effects to happen on every test run, such as API requests, package installation, or rocket launches.

We will mainly focus on mocking for the rest of the course and not spying, as it is hardly ever used in real projects.

Quick recap

In this lesson, we talked about mocking, its use cases, and objectives as well as its two flavours: mocking and spying.

Get hands-on with 1200+ tech skills courses.