Skip to content

Spy

Medium — good to knowTesting

ELI5 — The Vibe Check

A spy is like a double agent — it lets the real function still do its job, but secretly records everything: how many times it was called, with what arguments, what it returned. You spy on your own code without changing what it does.

Real Talk

A spy wraps a real function and records all calls to it without altering its behavior. You can assert after the fact that the function was called the right number of times, with the right arguments. It's a mock that still calls through to the real implementation.

Show Me The Code

import { vi } from 'vitest';

const consoleSpy = vi.spyOn(console, 'log');

logUserAction('click', 'button');

expect(consoleSpy).toHaveBeenCalledWith('USER_ACTION', 'click', 'button');
consoleSpy.mockRestore();

When You'll Hear This

"Add a spy to check that the analytics event fires on submit." / "The spy confirmed the callback was called twice, which explains the bug."

Made with passive-aggressive love by manoga.digital. Powered by Claude.