Suggest an editImprove this articleRefine the answer for “What is a mock function in the context of tests?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**A mock function (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. **Key point:** a mock function is not about the result, it is about behavior: it lets you track calls, arguments and order rather than computation.Shown above the full answer for quick recall.Answer (EN)ImageA 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."For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.