If you're writing tests for frontend applications and still not using jest.spyOn
, you're missing out on one of the most powerful tools Jest offers.
Let me show you why, when, and how to use it — with real examples that will level up your testing game.
💡 What is jest.spyOn
?
jest.spyOn
lets you monitor and control how a function behaves during a test — without changing the original implementation.
You can:
- Check if a function was called
- Control its return value
- Track how many times it was triggered
- Restore it after the test
🧪 Example 1: Spying on a Utility Function
// utils/date.js
export function formatDate(date) {
return new Intl.DateTimeFormat('en-US').format(date);
}
// components/Greeting.js
import { formatDate } from '../utils/date';
export function Greeting({ date }) {
return <p>Hello! Today is {formatDate(date)}</p>;
}
import * as dateUtils from '../utils/date';
test('calls formatDate with correct date', () => {
const spy = jest.spyOn(dateUtils, 'formatDate');
render(<Greeting date={new Date('2025-09-16')} />);
expect(spy).toHaveBeenCalledWith(new Date('2025-09-16'));
spy.mockRestore();
});
🧪 Example 2: Mocking a Function Temporarily
spy.mockReturnValue('September 16, 2025');
test('renders mocked date', () => {
const spy = jest.spyOn(dateUtils, 'formatDate').mockReturnValue('September 16, 2025');
const { getByText } = render(<Greeting date={new Date()} />);
expect(getByText(/September 16, 2025/)).toBeInTheDocument();
spy.mockRestore();
});
🧠 When to Use jest.spyOn
Use it when:
- You want to observe a function without replacing it
- You need to mock a function temporarily
- You’re testing side effects or interactions
- You want to avoid testing implementation details
🚫 When Not to Use It
Avoid jest.spyOn
when:
- You’re testing pure functions directly (use
jest.fn()
instead) - You’re mocking entire modules (use
jest.mock()
)
📌 Best Practices
- Always
mockRestore()
after your test to avoid side effects - Use
spy.mockImplementation()
for custom behavior - Keep your tests focused: spy only what’s necessary
🧨 Final Thoughts
jest.spyOn
is like a magnifying glass for your tests — it lets you zoom in on behavior without rewriting code. Use it wisely, and your tests will be cleaner, smarter, and more maintainable.
Liked this? Follow me for more practical testing tips and frontend insights. Let’s write code that’s not just functional — but testable and reliable.
Top comments (0)