top of page
Logo der Online Agentur mdwp


Mocks in React JS are predominantly used for testing by creating a mock function (also known as "spied" function) to replace the actual functionality within the application during test runs. They are especially useful for verifying interactions between functions and to ensure parts of the application function as expected within certain conditions.

A mock function gives us the ability to access information about those specific calls to the function, such as the number of times the function was called or what arguments were passed to the function for each call. It also allows us to implement custom return values.

Here is a simple example of a mock function:

// Assume we have a module called 'math' with a function 'add'
const math = require('./math');

// We can mock the 'add' function like this
math.add = jest.fn();

// Now we can force a return value
math.add.mockImplementation(() => 10);

// Calling the function now will always return 10
console.log(math.add(1, 2)); // Outputs: 10

// We can also see if and how the function was called
console.log(math.add.mock.calls); // Outputs: [[1, 2]]

In this example, the `math` module has an 'add' function that we want to mock. By using Jest's `fn()` function, we create a mock function and can then override its implementation with our own. In this case, we make it always return 10. After calling the function, we then log out the calls made to it, and we can see that our function was called with the arguments 1 and 2.

bottom of page