Skip to main content

What is a mock function in the context of tests?

A mock function (or mock) is a fake function that substitutes for the real one in tests, letting you control its behavior and check how the tested code interacts with it.


Why it is needed

Mock functions are used when:

  • calling the real function is undesirable (it makes a network request, hits a database, writes a file, calls a third-party service)
  • you need to check the fact of the call, not the result (for example, "is the function called, and with which arguments?")
  • you need to emulate different scenarios (success, error, delay, empty response)
  • the function under test depends on others, and those dependencies need to be isolated

What a mock function can do

It lets you:

  1. Replace the real call
  2. Supply the needed response (for example, return 42)
  3. Track calls: how many times it was called, with what arguments, in what order
  4. Check interaction, not computation

A simple example in Jest

js
const log = jest.fn(); // mock function log("hello"); expect(log).toHaveBeenCalled(); // check that the function was called at all expect(log).toHaveBeenCalledWith("hello"); // check that it was called with the right arguments

The main idea

A mock function is not about the result, it is about behavior. It lets you test the logic of the current piece of code without depending on "what is happening out there."

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.