Chuck's Academy

Testing JavaScript and DOM with Jest

Mocking and Stubbing in Jest

Mocking and Stubbing in Jest

In the world of testing, mocking and stubbing are essential techniques for isolating the code under test and controlling its dependencies. This section will explain what these techniques are and how to use them with Jest.

What is Mocking and Stubbing?

  • Mocking: Involves creating fake objects that simulate the behavior of real objects. This is used to test components in isolation.
  • Stubbing: Similar to mocking, but focuses more on replacing specific functions within objects with controlled implementations.

Mock Functions in Jest

Jest provides mocking functions that allow you to spy on the behavior of existing functions or replace them with simulations.

  1. Creating a Mock Function:
javascript
  1. Mocking Functions with Simulated Implementations:

You can provide a simulated implementation to a mock function using mockImplementation.

javascript
  1. Mocking Entire Modules:

You can mock entire modules using jest.mock. For example, suppose you have an api.js module:

javascript

You can mock this module in your tests:

javascript

Mocking Asynchronous Functions

You can mock asynchronous functions to simulate the resolution or rejection of promises:

javascript

Mocking Instance Methods

If you want to mock methods of a specific class, you can use jest.spyOn or overwrite the method directly:

javascript

Stubbing in Jest

To stub functions, you can temporarily replace their implementations:

javascript

Using Mock Clear and Reset

To avoid conflicts between tests, you can clear and reset mocks using mockClear or mockReset.

javascript

Full Example

Below is a complete example demonstrating mocking and stubbing for a function that depends on an API call:

javascript

With these mocking and stubbing techniques, you can isolate the code under test and simulate different controlled scenarios. In the next section, we will address user interaction testing with Jest, thus increasing our ability to ensure the quality and interactiveness of our application.


Ask me anything