Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 30 ยท Practice and Review

Jest Exercises with Solutions

Ten Jest exercises with full solutions covering matchers, errors, async code, mocks, fake timers and table tests, plus runnable stand-ins to check your answers.

Reading about tests is not the same as writing them. These ten exercises give you a small function each and ask you to write the tests that would catch real bugs. Try every exercise on paper or in your own project before you open the solution. The goal is not to match the solution word for word, but to cover the same cases.

Jest does not run on this site, so the exercises and solutions are read-only Jest code. To let you see the behavior anyway, two runnable stand-ins execute the functions under test and check the same ideas with Node's assert and mock.timers. They are stand-ins, not Jest, and they say so.

Ten exercises, five skills

Matchers Exercises 1 to 3.
Errors Exercise 4.
Async Exercises 5 and 6.
Mocks and timers Exercises 7 to 9.

Exercise 10 combines tables and snapshots.

1 / 2

Exercises 1 to 5: matchers, errors and promises

Exercise 1. Test clamp(value, min, max), which limits a number to a range. Cover below, inside, above and exactly on both limits.

Exercise 2. Test sumPrices(prices) for [0.1, 0.2]. A plain toBe(0.3) fails because of floating point. Pick a matcher that works.

Exercise 3. createUser(name) returns { id, name, createdAt }, where id is a number and createdAt changes with every run. Assert only the parts that are stable.

Exercise 4. parseAge(text) returns a whole number, or throws a RangeError with the message "age must be between 0 and 150" for anything else. Test both outcomes.

Exercise 5. fetchUser(id) returns a promise that resolves to { id, name }, and rejects with "invalid id" when id is zero or negative. Test both outcomes without the forgotten-await trap.

Solutions

JavaScript
// 1: boundaries on both sides
test.each([
  [-5, 0, 10, 0],   // below
  [5, 0, 10, 5],    // inside
  [15, 0, 10, 10],  // above
  [0, 0, 10, 0],    // exactly min
  [10, 0, 10, 10],  // exactly max
])("clamp(%i, %i, %i) is %i", (value, min, max, expected) => {
  expect(clamp(value, min, max)).toBe(expected);
});

// 2: floating point needs toBeCloseTo
test("sums prices without float surprises", () => {
  expect(sumPrices([0.1, 0.2])).toBeCloseTo(0.3);
});

// 3: asymmetric matchers for the unstable parts
test("creates a user", () => {
  expect(createUser("Ada")).toEqual({
    id: expect.any(Number),
    name: "Ada",
    createdAt: expect.any(Date),
  });
});

// 4: wrap the call, check the type and the message
test("rejects an impossible age", () => {
  expect(() => parseAge("abc")).toThrow(RangeError);
  expect(() => parseAge("200")).toThrow("age must be between 0 and 150");
});
test("accepts a valid age", () => {
  expect(parseAge("42")).toBe(42);
});

// 5: return or await the promise, and count assertions
test("fetchUser resolves", async () => {
  await expect(fetchUser(1)).resolves.toEqual({ id: 1, name: "Ada" });
});
test("fetchUser rejects an invalid id", async () => {
  expect.assertions(1);
  await expect(fetchUser(0)).rejects.toThrow("invalid id");
});

If you used toBe for the object in exercise 3 or skipped expect.any, revisit Common Matchers and Arrays and Objects. For exercise 4, the wrapper arrow function matters: calling parseAge("abc") directly would throw before expect ever ran, as explained in Errors and Custom Matchers.

Check your answers with a stand-in

This stand-in implements the five functions and checks the same ideas with assert. closeTo imitates toBeCloseTo, and assert.rejects plays the role of .rejects.

Node.js Stand-in: functions and checks for exercises 1 to 5

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.

Exercises 6 to 10: async traps, mocks, timers and tables

Exercise 6. This test always passes, even though loadTotal() returns 99 instead of 100. Find the bug and fix it.

JavaScript
test("loads the total", () => {
  expect(loadTotal()).resolves.toBe(100);
});

Exercise 7. notifyAll(users, send) calls send(user.email, message) once per user. Test it with a mock function: the call count and the arguments of each call.

Exercise 8. checkout(amount) calls console.warn with a message containing "negative" when the amount is below zero. Test that, without printing noise into the test report, and without leaking the spy.

Exercise 9. debounce(fn, 200) returns a function that calls fn only after 200 ms of quiet. Test it without waiting for real time.

Exercise 10. slugify(title) turns "Hello, World!" into "hello-world". Write a table with at least six rows, including edge cases such as extra spaces, symbols only and an empty string.

Solutions

JavaScript
// 6: the promise is not returned or awaited, so the test ends first
test("loads the total", async () => {
  await expect(loadTotal()).resolves.toBe(100);
});

// 7: one mock, call count, argument checks
test("notifies every user", () => {
  const send = jest.fn();
  notifyAll([{ email: "[email protected]" }, { email: "[email protected]" }], send);

  expect(send).toHaveBeenCalledTimes(2);
  expect(send).toHaveBeenNthCalledWith(1, "[email protected]", expect.any(String));
  expect(send).toHaveBeenLastCalledWith("[email protected]", expect.any(String));
});

// 8: spy, silence, assert, restore
test("warns about negative amounts", () => {
  const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
  checkout(-5);
  expect(warn).toHaveBeenCalledWith(expect.stringContaining("negative"));
  warn.mockRestore();
});

// 9: fake timers
test("debounce calls once after the quiet period", () => {
  jest.useFakeTimers();
  const fn = jest.fn();
  const debounced = debounce(fn, 200);

  debounced("a");
  jest.advanceTimersByTime(150);
  debounced("b");              // restarts the wait
  jest.advanceTimersByTime(199);
  expect(fn).not.toHaveBeenCalled();

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

// 10: table with edge cases
test.each([
  ["Hello, World!", "hello-world"],
  ["  extra   spaces  ", "extra-spaces"],
  ["Already-slugged", "already-slugged"],
  ["C++ & Rust", "c-rust"],
  ["!!!", ""],
  ["", ""],
])("slugify(%j) is %j", (input, expected) => {
  expect(slugify(input)).toBe(expected);
});

The solution to exercise 9 is the interesting one: it checks both sides of the boundary (199 ms is too early, 200 ms is exactly on time) and that only the last arguments are used. See Mocking Timers, Dates and HTTP if fake timers are still unfamiliar.

Run the second set as a stand-in

Node.js Stand-in: the forgotten await, a debounce and a slug table

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.

Notice what the first two lines of output teach: the same buggy test is green or red depending only on whether the promise was awaited. That is why the expect.assertions habit from Testing Promises and Async/Await is worth the extra line.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which matcher should you use to compare 0.1 + 0.2 with 0.3?

    Floating point sums are not exact, so compare within a small tolerance using toBeCloseTo.
  2. 2. Why is expect(promise).resolves.toBe(1) without await or return a bug?

    The assertion is itself asynchronous. Without await or return, the test function ends first and Jest never sees the failure.
  3. 3. In the debounce test, why advance 199 ms and then 1 ms?

    199 ms must not call the function and 200 ms must, which proves the delay is exactly right.
  4. 4. Why restore a console.warn spy at the end of the test?

    An unrestored spy stays installed and hides output or leaks call history into other tests.

Summary

  • Practice by writing the case list first, then the tests, then comparing with a solution.
  • Use toBeCloseTo for floats, expect.any for unstable values and a wrapper function for toThrow.
  • Always await (or return) promise assertions; add expect.assertions where a skipped assertion would hide a bug.
  • Mocks, spies and fake timers each need cleanup so tests stay independent.
  • A table of edge cases (empty, symbols only, extra spaces) catches more bugs than one happy-path test.

Ready to talk about all of this in an interview? Continue with Jest Interview Questions.