---
title: "Fake the clock and the network in unit · Agent Wranglers"
url: https://agentwranglers.se/playbook/testing/unit-tests/unit-deterministic
updated: 2026-10-20
licence: "All rights reserved"
---

# Fake the clock and the network in unit tests

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Unit tests](https://agentwranglers.se/playbook/testing/unit-tests)
- Rule: Unit tests never depend on the clock, random numbers or the network. They pass on any day, on any machine.
- How: Pass the clock and the random source in as arguments, or use fake timers such as `vi.useFakeTimers()` in Vitest or `jest.useFakeTimers()` in Jest. In Python, freeze time with a library such as time-machine. Restore the system clock after each test, even when it fails. Seed every random source. Block network calls in unit tests, for example with pytest-socket.
- Check: Run the suite in two far-apart time zones, such as `TZ=Pacific/Kiritimati` and `TZ=Pacific/Pago_Pago`. Run it with the date moved a year ahead, such as with `faketime '+365d'`. Then run it with the network off, such as in a container started with `--network none`. All runs pass.

Example:

```js
import { vi, test, expect, afterEach } from 'vitest';

afterEach(() => { vi.useRealTimers(); });

test('a trial ends after 14 days', () => {
  vi.useFakeTimers();
  vi.setSystemTime(new Date('2026-03-01T00:00:00Z'));
  const trial = startTrial();
  vi.setSystemTime(new Date('2026-03-15T00:00:01Z'));
  expect(trial.isActive()).toBe(false);
});
```

```python
# pytest with time-machine
import time_machine

def test_a_trial_ends_after_14_days():
    with time_machine.travel("2026-03-01T00:00:00Z", tick=False) as traveller:
        trial = start_trial()
        traveller.move_to("2026-03-15T00:00:01Z")
        assert not trial.is_active()
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers testing playbook: https://agentwranglers.se/playbook/testing/unit-tests/unit-deterministic`.

- Previous: [Test behaviour through the public interface](https://agentwranglers.se/playbook/testing/unit-tests/unit-behaviour)
- Next: [Test the edges and the errors](https://agentwranglers.se/playbook/testing/unit-tests/test-the-edges)
- [Unit tests](https://agentwranglers.se/playbook/testing/unit-tests)
