0
0
JavascriptHow-ToBeginner · 3 min read

How to Mock Function in JavaScript Test: Simple Guide

To mock a function in JavaScript tests, use jest.fn() to create a mock function or jest.spyOn() to spy on existing functions. These mocks let you control and check how functions are called during tests.
📐

Syntax

There are two main ways to mock functions in JavaScript tests using Jest:

  • jest.fn(): Creates a new mock function you can customize.
  • jest.spyOn(object, 'method'): Replaces an existing method on an object with a mock, allowing you to track calls.

Both let you check calls, arguments, and return values.

javascript
const mockFunction = jest.fn();

const spy = jest.spyOn(object, 'method');
💻

Example

This example shows how to mock a simple function and check if it was called with the right arguments.

javascript
// Function to test
function greet(callback) {
  callback('Hello');
}

// Test
const mockCallback = jest.fn();
greet(mockCallback);

console.log(mockCallback.mock.calls.length); // Number of times called
console.log(mockCallback.mock.calls[0][0]); // First call, first argument
Output
1 Hello
⚠️

Common Pitfalls

Common mistakes when mocking functions include:

  • Not resetting mocks between tests, causing false positives.
  • Mocking the wrong function or object.
  • Forgetting to restore original functions after spying.

Always use mockClear() or mockReset() to clear mocks, and mockRestore() to restore spied functions.

javascript
const obj = {
  method: () => 'real',
};

// Wrong: forgetting to restore
const spy = jest.spyOn(obj, 'method').mockReturnValue('mocked');
console.log(obj.method()); // mocked

// After test
spy.mockRestore();
console.log(obj.method()); // real
Output
mocked real
📊

Quick Reference

MethodPurposeUsage Example
jest.fn()Create a new mock functionconst mock = jest.fn();
jest.spyOn()Spy on existing object methodjest.spyOn(obj, 'method');
mockClear()Clear mock call historymock.mockClear();
mockReset()Reset mock implementation and historymock.mockReset();
mockRestore()Restore original function after spyspy.mockRestore();

Key Takeaways

Use jest.fn() to create simple mock functions for testing calls and arguments.
Use jest.spyOn() to mock and track existing object methods safely.
Always clear or reset mocks between tests to avoid interference.
Restore original functions after spying to keep tests isolated.
Check mock call counts and arguments to verify function behavior.