Search⌘ K
AI Features

Introduction to Mocking

Explore the concept of mocking in Jest and understand how it isolates code by simulating external dependencies. Learn why mocking is essential for controlled, reliable testing and how it overcomes environment limitations, providing access to otherwise unavailable code aspects.

What is mocking?

In testing, mocking is the practice of stubbing out something that our code depends on. In a low-level sense, we can think of all the arguments we’ve created to pass into our functions being tested as mock arguments. They are unrelated to the real-world source the function receives arguments from, but instead exist solely for testing purposes.

What types of things do we mock?

As a general rule, we want to mock any external dependencies in our code, like third-party packages, as well as data received or passed into our code. In some instances, we may want to mock local modules that our code depends on as well, such as a class or an API call. Additionally, mocking specific functions can be extremely helpful. This is particularly true in testing client-side code. Often, when assembling components, a function such as a change handler is passed into the component. Since the function is defined outside the component, it isn’t the behavior of the ...