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
| Method | Purpose | Usage Example |
|---|---|---|
| jest.fn() | Create a new mock function | const mock = jest.fn(); |
| jest.spyOn() | Spy on existing object method | jest.spyOn(obj, 'method'); |
| mockClear() | Clear mock call history | mock.mockClear(); |
| mockReset() | Reset mock implementation and history | mock.mockReset(); |
| mockRestore() | Restore original function after spy | spy.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.