Skip to content
Latchkey

What Is a Mock?

A mock is a fake object that stands in for a real dependency in a test and verifies how your code interacts with it.

When the code under test depends on something slow, external, or hard to control, like a payment gateway or an email service, you replace it with a mock. A mock not only returns canned answers but also records and asserts on how it was called, so you can verify behavior without touching the real system.

What a mock does

A mock replaces a real collaborator with a programmable stand-in. You configure what it returns and then assert that your code called it the right way, with the right arguments, the right number of times. The verification of interaction is what distinguishes a mock from a plain stub.

A worked example

When testing a notifier, you mock the email client and assert that send was called once with the expected recipient, without ever sending real mail.

A mock verifying an interaction
const email = { send: jest.fn() };
notifyUser(email, "ada@example.com");
expect(email.send).toHaveBeenCalledWith("ada@example.com");

Mocks among the test doubles

  • Stub: returns canned values, no interaction checks.
  • Mock: returns values and verifies how it was called.
  • Spy: wraps a real object and records calls to it.
  • Fake: a working but simplified implementation.

When mocks help and hurt

Mocks make unit tests fast and deterministic by removing external dependencies. Over-mocking, though, can produce tests that pass while the real integration is broken, because they assert against your assumptions rather than reality. Balance mock-heavy unit tests with a few real integration tests.

Mocks and CI reliability

Because mocks remove network and I/O, well-mocked unit tests are fast and rarely flaky in CI. The flakiness tends to live in the unmocked integration and E2E layers, where transient failures are common. Latchkey auto-retries those transient flakes so a real-dependency hiccup does not fail an otherwise green build.

Key takeaways

  • A mock replaces a real dependency and verifies how it was called.
  • Verification of interaction is what sets mocks apart from stubs.
  • Over-mocking risks green tests over a broken real integration.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →