Test Spies Explained: Observe Calls Without Intercepting Them

Test Spies Explained: Observe Calls Without Intercepting Them

A test spy sits between your code and a real dependency. It lets the real call happen while recording everything: how many times it was called, with what arguments, and what it returned. This makes spies useful in a narrow but important set of scenarios where neither mocks nor stubs are the right fit.

The Spy's Unique Position

Most test doubles replace a dependency. A spy wraps it. The real function runs; the spy just takes notes.

// Jest spy on a real method
import * as analytics from './analytics';

test('tracks page view on navigation', () => {
  const spy = jest.spyOn(analytics, 'trackEvent');
  // analytics.trackEvent still runs — spy just observes
  
  navigateTo('/dashboard');
  
  expect(spy).toHaveBeenCalledWith('page_view', { path: '/dashboard' });
  
  spy.mockRestore(); // put the real function back
});

The difference from a mock: analytics.trackEvent actually executes. With a mock (jest.fn()), it would be replaced with a no-op.

When Spies Are the Right Tool

Verifying calls into a real dependency without replacing it. If the dependency has useful side effects or returns data your test needs, a spy lets you observe without interrupting.

Testing that a function delegates correctly. If calculateTotal should call applyDiscount under certain conditions, spy on applyDiscount to confirm — while still letting the real discount logic run and contribute to the result.

Checking call counts or argument patterns in legacy code. Spies work on any object method without requiring dependency injection.

Wrapper/facade classes. If you're testing a thin wrapper around a library, a spy confirms the wrapper passes the right arguments without mocking away the library itself.

Spies in Python: unittest.mock.spy_open and wraps

Python's unittest.mock doesn't have a dedicated "spy" concept, but wraps achieves the same thing.

from unittest.mock import patch, MagicMock
import myapp.cache as cache_module

def test_caches_result_on_first_call(mocker):
    # Spy: wraps the real function, lets it execute
    spy = mocker.patch.object(
        cache_module,
        'set_cache',
        wraps=cache_module.set_cache
    )
    
    result = get_user_profile(user_id='u1')
    
    assert result.name == 'Alice'  # real data came back
    spy.assert_called_once_with('profile:u1', result)  # call was recorded

With wraps=, the real set_cache function runs. The mocker.patch.object just adds recording around it.

Spies in Java: Mockito's @Spy

Mockito's @Spy annotation creates a spy around a real object. Unlike @Mock, the spy calls real methods unless you explicitly stub them.

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    
    @Spy
    private DiscountCalculator discountCalculator = new DiscountCalculator();
    
    @Mock
    private OrderRepository orderRepo;
    
    @InjectMocks
    private OrderService orderService;
    
    @Test
    void appliesDiscountForPremiumUsers() {
        User premiumUser = new User(id: "u1", tier: "premium");
        Order order = new Order(amount: 100.0);
        
        double total = orderService.processOrder(order, premiumUser);
        
        // Real discount logic ran
        assertEquals(90.0, total, 0.001);
        
        // And we can verify it was called
        verify(discountCalculator).calculateDiscount(premiumUser, order);
    }
}

The spy lets DiscountCalculator.calculateDiscount run its real logic (10% premium discount), while the verify() call confirms it was invoked. A full mock would replace the logic with a no-op.

Partial Spying: Stub Some Methods, Keep Others

Sometimes you want to spy on a class but stub one expensive or side-effect-heavy method.

@Spy
private UserService userService = new UserService(realRepo);

@Test
void sendsBirthdayEmailsToActiveUsers() {
    // Stub just the email method — don't actually send
    doNothing().when(userService).sendBirthdayEmail(any());
    
    // Real logic runs for finding users
    userService.processBirthdayEmails();
    
    // Verify the right users got email calls
    verify(userService, times(3)).sendBirthdayEmail(any(User.class));
}

This is useful when a class has both logic you want to test and I/O you want to avoid. Partial spying lets you split them.

Sinon.js Spy Details

Sinon provides the most feature-rich spy API in the JavaScript ecosystem.

const sinon = require('sinon');
const mailer = require('./mailer');

describe('notification service', () => {
  let sendEmailSpy;
  
  beforeEach(() => {
    sendEmailSpy = sinon.spy(mailer, 'sendEmail');
  });
  
  afterEach(() => {
    sendEmailSpy.restore();
  });
  
  it('sends one email per recipient', () => {
    const recipients = ['a@example.com', 'b@example.com', 'c@example.com'];
    notifyAll(recipients, 'System maintenance at midnight');
    
    // Call count
    sinon.assert.callCount(sendEmailSpy, 3);
    
    // Argument assertions
    sinon.assert.calledWith(sendEmailSpy.firstCall, 'a@example.com', sinon.match.string);
    
    // Return value tracking
    const returnValues = sendEmailSpy.returnValues;
    returnValues.forEach(rv => expect(rv).toBeTruthy());
  });
});

Sinon spies track: callCount, calledWith(), returnValues, exceptions, thisValues, and individual Call objects for each invocation.

The Restore Step (Non-Negotiable)

Spies on real objects mutate global state. If you don't restore them:

  • Other tests see the spy instead of the real function
  • Call counts accumulate across tests
  • Test order becomes significant (bad)
// Jest: use mockRestore() in afterEach
afterEach(() => {
  jest.restoreAllMocks();
});

// Or per-spy:
afterEach(() => {
  spy.mockRestore();
});
# pytest-mock: patches are restored automatically after each test
# but manual patch.stop() is needed outside of mocker context
// Mockito: @Spy is reset between tests with @ExtendWith(MockitoExtension.class)

Spy vs Mock: The Decision

You need to... Use
Verify a call happened but not care about behavior Mock
Verify a call happened AND keep real behavior Spy
Replace behavior entirely Mock or Stub
Observe calls on a class you can't inject Spy
Verify call count on a partial implementation Spy

The cleanest code rarely needs spies — good dependency injection means you can fully replace dependencies with mocks or stubs. But in legacy code, integration test scenarios, or when testing delegation within a class hierarchy, spies are the right tool.

Read more

Start now free