# Mocks

> The Mocks are objects in testing that simulate the behavior of real objects in a controlled way to verify interactions and responses.

## What is a mock in testing and when should I use one?

The simulated objects used in testing to mimic the behavior of real objects, allowing testers to verify interactions and check if certain methods are called. They help isolate units and ensure that dependencies are correctly handled.

- Topic: Testing
- Type: concept

## Example

Wrong:

```ts
const send = vi.fn();
await signUp('ann@example.com', { send });
expect(send).toHaveBeenCalled();
```

Right:

```ts
const send = vi.fn();
await signUp('ann@example.com', { send });
expect(send).toHaveBeenCalledWith(
  'ann@example.com',
  expect.stringContaining('Welcome'),
);
```

Checking the arguments proves the right email went to the right person, not just that some call happened.

## Common mistakes

- Mocking so much that the test only checks the mocks, not the real code.
- Forgetting to restore a mock, so other tests fail in strange ways.
- Mocks that drift from the real API, so tests pass while production breaks.

## Key points

- Mocks replace dependencies like email, payments or the network, never the module under test.
- Assertions check call arguments with `toHaveBeenCalledWith()`, not only that a call happened.
- Mocks are reset or restored between tests so state does not leak.

## Interview questions

### Mock vs stub: what is the difference?

A stub only returns preset data. A mock also records calls so the test can verify how it was used.

### Is mocking bad practice?

No, but overuse is. Mock slow or external boundaries and test your own logic with real code.

### How do I reset mocks between tests?

Call `vi.restoreAllMocks()` or `jest.restoreAllMocks()` in `afterEach`, or enable the restore option in the test config.

## Related cards

- [Stubs](https://wonderium.dev/engineering/stubs.md)
- [Dummy Objects](https://wonderium.dev/engineering/dummy-objects.md)
- [Unit Test](https://wonderium.dev/engineering/unit-test.md)
- [Integration Test](https://wonderium.dev/engineering/integration-test.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/mocks
- Last updated: 2026-11-25
