Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 30 ยท Mocking

Mocking Timers, Dates and HTTP

Test time and network code in Jest: useFakeTimers, advanceTimersByTime, setSystemTime, async timer helpers and mocking fetch, with runnable node:test stand-ins.

Two things make tests slow and flaky: waiting for time to pass, and talking to the network. A debounce function that waits 500 milliseconds would make every test take half a second. A report that prints "today's date" fails tomorrow. A function that calls an API fails when the Wi-Fi drops.

The fix is to take control. Jest can replace the clock with a fake clock that you move forward by hand, and you can replace fetch with a function that returns a canned response. Then the tests are instant and give the same answer every time.

The real Jest functions need Jest, so the Jest code below is read-only. The runnable stand-ins use Node's node:test mock timers and mock.method, which implement the same ideas, and they say so.

Take control of the world

Fake timers setTimeout and setInterval wait for you.
Fake date Pin "now" to a known moment.
Fake network fetch returns a canned response.

The result is fast, repeatable tests.

1 / 2

Fake timers

Here is a function that runs a callback after a delay:

JavaScript
function delay(callback, ms) {
  setTimeout(callback, ms);
}

Testing it with the real clock means waiting. With fake timers you jump ahead:

JavaScript
beforeEach(() => {
  jest.useFakeTimers();
});

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

test("the callback runs after 1000 ms", () => {
  const callback = jest.fn();

  delay(callback, 1000);

  jest.advanceTimersByTime(999);
  expect(callback).not.toHaveBeenCalled();

  jest.advanceTimersByTime(1);
  expect(callback).toHaveBeenCalledTimes(1);
});

jest.useFakeTimers() replaces setTimeout, setInterval, setImmediate, clearTimeout and friends (and also Date, by default in modern Jest) with controllable versions. Nothing fires by itself. You decide how much time passes.

The main controls:

Call What it does
jest.advanceTimersByTime(ms) Moves the clock forward and runs every timer that becomes due, in order.
jest.runOnlyPendingTimers() Runs the timers that are scheduled right now, but not new ones they create.
jest.runAllTimers() Keeps running until no timers are left (loops forever on a repeating setInterval, and Jest stops after a limit).
jest.advanceTimersToNextTimer() Jumps to the next scheduled timer and runs it.
jest.getTimerCount() How many timers are waiting.
jest.clearAllTimers() Drops all pending timers.

A debounce is a perfect case:

JavaScript
test("debounce calls the function once, after the quiet period", () => {
  const save = jest.fn();
  const debouncedSave = debounce(save, 300);

  debouncedSave("a");
  jest.advanceTimersByTime(100);
  debouncedSave("b");
  jest.advanceTimersByTime(299);
  expect(save).not.toHaveBeenCalled();

  jest.advanceTimersByTime(1);
  expect(save).toHaveBeenCalledTimes(1);
  expect(save).toHaveBeenCalledWith("b");
});

Promises and fake timers

Promise callbacks are not timers: fake timers do not run them. If your code awaits something and then sets a timer, the timer may not exist yet when you advance the clock. Jest provides async versions that let pending promises run in between:

JavaScript
test("retries after a delay", async () => {
  const attempt = jest.fn()
    .mockRejectedValueOnce(new Error("busy"))
    .mockResolvedValueOnce("ok");

  const promise = retry(attempt, { delayMs: 1000 });

  await jest.advanceTimersByTimeAsync(1000);

  await expect(promise).resolves.toBe("ok");
  expect(attempt).toHaveBeenCalledTimes(2);
});

The methods advanceTimersByTimeAsync, runAllTimersAsync and runOnlyPendingTimersAsync exist in current Jest versions. Prefer them whenever the code under test mixes await and timers. For the basics of async tests see Testing Promises and Async/Await.

Always switch back with jest.useRealTimers() (for example in afterEach). A test that leaves fake timers on can make later tests hang, because their setTimeout calls never fire.

Fake dates

Modern fake timers also control Date. To pin the current time to a known instant, use jest.setSystemTime:

JavaScript
beforeEach(() => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date("2030-01-15T10:00:00Z"));
});

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

test("an invoice is due 30 days after today", () => {
  const invoice = createInvoice();

  expect(invoice.dueDate.toISOString()).toBe("2030-02-14T10:00:00.000Z");
});

You can pass the starting time directly: jest.useFakeTimers({ now: new Date("2030-01-15") }). While the fake clock is on, new Date() and Date.now() return the fake time and move only when you advance timers or call setSystemTime again. To fake only the clock and leave timers alone, use the doNotFake option listed in the Jest docs for your version.

Use UTC dates and toISOString() in assertions. A test that prints the local time zone gives different answers on different computers.

Mocking HTTP with fetch

Your tests should not call real servers. Replace fetch with a mock that returns a canned Response. In Node 18 and later, fetch and Response are built in, so you can use them directly:

JavaScript
async function getUserName(id) {
  const response = await fetch(`https://api.example.com/users/${id}`);
  if (!response.ok) {
    throw new Error(`request failed with ${response.status}`);
  }
  const data = await response.json();
  return data.name;
}
JavaScript
afterEach(() => {
  jest.restoreAllMocks();
});

test("returns the user's name", async () => {
  const fetchSpy = jest.spyOn(globalThis, "fetch").mockResolvedValue(
    new Response(JSON.stringify({ id: 7, name: "Ada" }), { status: 200 })
  );

  await expect(getUserName(7)).resolves.toBe("Ada");
  expect(fetchSpy).toHaveBeenCalledWith("https://api.example.com/users/7");
});

test("throws on a server error", async () => {
  jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response("oops", { status: 500 }));

  await expect(getUserName(7)).rejects.toThrow("request failed with 500");
});

test("rejects when the network fails", async () => {
  jest.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("fetch failed"));

  await expect(getUserName(7)).rejects.toThrow("fetch failed");
});

Three tests cover the three paths: success, an HTTP error status, and a network failure. This is the real value of mocking: you can reach the failure branches that a healthy server will never let you test. Spying on globalThis.fetch is the same technique you saw in Spying with jest.spyOn.

In a jsdom test environment, fetch may not exist, depending on your Jest and Node versions. Define it in a setup file or spy on a function you inject instead.

Libraries such as msw (Mock Service Worker) intercept requests at a lower level and let you describe the fake server once. They are an alternative when many tests share the same fake API, but a hand-made fetch mock is enough for most cases.

Stand-in 1: fake timers with node:test

Node's mock.timers offers the same model: enable it, tick the clock, check results. Here it runs a debounce without waiting. This is real Node code, but its names differ from Jest's (tick instead of advanceTimersByTime), so treat it as a stand-in for the concept.

Node.js A debounce tested with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The whole run takes a few milliseconds, yet the code under test saw 400 ms go by. Only the last call ("b") was saved, because the first one was cancelled by the second.

Stand-in 2: mocking fetch

This stand-in uses mock.method on globalThis.fetch to run the three paths from the Jest example: success, a 500 and a network error. No request leaves your machine.

Node.js Three paths through a fetch call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Habits that keep time and HTTP tests healthy

  • Enable fake timers per test (or per describe) and switch back afterward.
  • Pin dates in UTC and compare ISO strings.
  • Mock at the narrowest point: fetch, not your whole API module, so your request-building code still runs.
  • Test the unhappy paths. A mock makes errors as easy to produce as successes.
  • Do not assert on exact elapsed milliseconds measured by the real clock; assert on what fake time allows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After jest.useFakeTimers(), a setTimeout of 1000 ms is scheduled. When does its callback run?

    Fake timers only fire when you move the clock, so the test decides how much time passes.
  2. 2. Which call pins the current date to a known moment while fake timers are on?

    setSystemTime sets what new Date() and Date.now() return under the fake clock.
  3. 3. Your code awaits a promise and then calls setTimeout. Which helper is the safest way to move time forward in the test?

    The async helpers flush promise callbacks between timers, so timers created after an await exist when the clock moves.
  4. 4. Why is mocking fetch useful for error handling?

    A real server rarely fails when you want it to. A mock can return any status or throw any error instantly.

Summary

  • jest.useFakeTimers() makes time stand still until you call advanceTimersByTime, runOnlyPendingTimers or runAllTimers; undo it with jest.useRealTimers().
  • Use the ...Async timer helpers when code mixes promises and timers.
  • jest.setSystemTime pins Date so date logic is repeatable; assert with UTC ISO strings.
  • Spy on globalThis.fetch and return new Response(...) or reject to test success, HTTP errors and network failures without a network.
  • Always restore timers and spies so tests stay independent.

Next, see how to capture complex output once and compare it later in Snapshot Testing.