Hiprup

What are test doubles (mocks, stubs, spies)?

Test doubles are stand-ins for real dependencies, so you can test a unit in isolation.

  • Mock — a fake with expectations about how it's called; verifies interactions.

  • Stub — returns canned responses to control inputs.

  • Spy — wraps a real or fake function and records how it was called.

Use them to isolate the code under test from databases, networks, or time.

// Jest examples

// Stub — return predetermined value
const getUser = jest.fn().mockReturnValue({ id: 1, name: 'John' });
const user = getUser(); // { id: 1, name: 'John' }

// Mock — verify interactions
const sendEmail = jest.fn();
userService.register('john@test.com');
expect(sendEmail).toHaveBeenCalledWith('john@test.com', 'Welcome');
expect(sendEmail).toHaveBeenCalledTimes(1);

// Spy — wrap real function
const spy = jest.spyOn(console, 'log');
myFunction();
expect(spy).toHaveBeenCalledWith('expected output');
spy.mockRestore(); // Restore original

// Mock implementation
const fetchData = jest.fn().mockImplementation(async (id) => {
  return { id, name: 'Mock User' };
});

jest.fn() creates a stub/mock. mockReturnValue sets the return value. toHaveBeenCalledWith verifies the call arguments. toHaveBeenCalledTimes verifies call count. jest.spyOn wraps a real method while tracking calls. mockRestore restores the original implementation.

Know the three types: stub (control return), mock (verify interaction), spy (track without changing). In Jest: jest.fn() for stubs/mocks, jest.spyOn for spies. toHaveBeenCalledWith and toHaveBeenCalledTimes for verification. mockRestore for cleanup.

What are test doubles (mocks, stubs, spies)? | Hiprup