Mocks and test doubles

suggest change

A test double is any generic replacement object used in place of a production dependency during automated testing. Test doubles isolate the code under test, eliminate nondeterministic network latency, and simulate edge cases (such as network timeouts or server 500 errors).

According to Gerard Meszaros' standard classification, test doubles fall into five categories:

  1. Dummy: Objects passed around but never actually used (e.g., filling a required parameter).
  2. Stub: Objects providing canned responses to method calls without verifying interaction.
  3. Spy: Objects wrapping real methods to record invocation count, arguments, and return values.
  4. Mock: Objects pre-programmed with specific behavioral expectations that fail the test if not called as expected.
  5. Fake: Working implementations that take shortcuts unsuitable for production (e.g., an in-memory Map database).

1. Native Test Doubles with node:test

Modern Node.js (v18+) includes a built-in test runner (node:test) equipped with native mocking capabilities:

Function Spies and Stubs with mock.fn

import { test, mock } from 'node:test';
import assert from 'node:assert/strict';

test('mock.fn tracks calls and overrides return values', () => {
  // Create a stub function returning a fixed value
  const calculateTax = mock.fn((subtotal) => subtotal * 0.1);

  const result = calculateTax(100);

  assert.equal(result, 10);
  assert.equal(calculateTax.mock.callCount(), 1);
  assert.deepEqual(calculateTax.mock.calls[0].arguments, [100]);
});

Spying on Existing Object Methods with mock.method

import { test, mock } from 'node:test';
import assert from 'node:assert/strict';

const paymentGateway = {
  async charge(amount) {
    // Real implementation would talk to Stripe/PayPal
    return { status: 'success', transactionId: 'tx_123' };
  }
};

test('spies on payment gateway charge method', async () => {
  // Spy and stub the charge method
  const chargeMock = mock.method(paymentGateway, 'charge', async (amount) => {
    return { status: 'success', transactionId: 'mock_tx_999' };
  });

  const response = await paymentGateway.charge(50.00);

  assert.equal(response.transactionId, 'mock_tx_999');
  assert.equal(chargeMock.mock.callCount(), 1);

  // Restore original implementation
  chargeMock.mock.restore();
});

Mocking System Timers

import { test, mock } from 'node:test';
import assert from 'node:assert/strict';

test('fast-forwards timer delays without waiting', (t) => {
  mock.timers.enable({ apis: ['setTimeout'] });

  let completed = false;
  setTimeout(() => {
    completed = true;
  }, 10_000); // 10 second delay

  assert.equal(completed, false);

  // Advance time by 10,000 milliseconds instantaneously
  mock.timers.tick(10_000);

  assert.equal(completed, true);
  mock.timers.reset();
});

2. Using Sinon.js (Spies, Stubs, and Mocks)

For richer assertion matchers across various testing frameworks (like Mocha or Jest), Sinon.js is the most widely adopted library:

npm install --save-dev sinon
import sinon from 'sinon';
import assert from 'node:assert/strict';

// Service under test
class OrderService {
  constructor(emailService, paymentGateway) {
    this.emailService = emailService;
    this.paymentGateway = paymentGateway;
  }

  async processOrder(user, amount) {
    const payment = await this.paymentGateway.charge(amount);
    if (payment.ok) {
      await this.emailService.sendReceipt(user.email, amount);
    }
    return payment.ok;
  }
}

describe('OrderService', () => {
  let emailServiceStub;
  let paymentGatewayStub;
  let orderService;

  beforeEach(() => {
    emailServiceStub = {
      sendReceipt: sinon.stub().resolves(true)
    };
    paymentGatewayStub = {
      charge: sinon.stub()
    };
    orderService = new OrderService(emailServiceStub, paymentGatewayStub);
  });

  afterEach(() => {
    sinon.restore(); // Cleans up all stubs
  });

  it('sends receipt when charge succeeds', async () => {
    paymentGatewayStub.charge.withArgs(100).resolves({ ok: true });

    const success = await orderService.processOrder({ email: 'alice@example.com' }, 100);

    assert.equal(success, true);
    sinon.assert.calledOnceWithExactly(emailServiceStub.sendReceipt, 'alice@example.com', 100);
  });

  it('does not send receipt when charge fails', async () => {
    paymentGatewayStub.charge.resolves({ ok: false });

    const success = await orderService.processOrder({ email: 'alice@example.com' }, 100);

    assert.equal(success, false);
    sinon.assert.notCalled(emailServiceStub.sendReceipt);
  });
});

3. Mocking External HTTP APIs with nock

Instead of mocking internal service classes, test network boundaries by intercepting outbound HTTP requests:

npm install --save-dev nock
import nock from 'nock';
import assert from 'node:assert/strict';

// Intercepts outgoing HTTP calls to https://api.weather.com
const scope = nock('https://api.weather.com')
  .get('/v1/current?city=Seattle')
  .reply(200, {
    temperature: 58,
    condition: 'Rainy'
  });

// Calling production code that issues fetch() or http.get()
const res = await fetch('https://api.weather.com/v1/current?city=Seattle');
const data = await res.json();

assert.equal(data.temperature, 58);
assert.equal(scope.isDone(), true); // Verifies the HTTP mock was called

4. Best Practices for Test Doubles

  1. Favor Stubs over Mocks: Stubs verify state (outputs); mocks verify implementation details (behavior). State-based assertions make tests resilient to internal code refactorings.
  2. Never Mock What You Don't Own: Prefer mocking adapters and interfaces that your team controls, or mock at the network boundary using tools like nock or MSW.
  3. Always Reset in afterEach(): Residual mock state leaking into subsequent tests creates brittle, order-dependent test failures. Always call sinon.restore() or mock.reset().
  4. Use Fakes for Complex State: For dependencies with stateful lifecycles (like key-value caches or repositories), an in-memory class with an internal Map is cleaner and easier to maintain than dozens of individual method stubs.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents