Comparing numbers in tests goes beyond simple equality. This lesson covers Jest's range comparison matchers and the special matcher needed for floating point numbers.
Comparing Numbers with Range Matchers
Jest provides four range comparison matchers that mirror standard math operators: .toBeGreaterThan(), .toBeGreaterThanOrEqual(), .toBeLessThan(), and .toBeLessThanOrEqual(). Each takes a number to compare the received value against.
These read naturally and produce clear failure messages, which is an improvement over manually writing expect(value > 10).toBe(true).
.toBeCloseTo(number, numDigits?) avoids floating point rounding errors in comparisons.
0.1 + 0.2 === 0.3 is false in JavaScript due to binary floating point representation.
The second argument controls precision (decimal digits); it defaults to 2.
Never use .toBe() to compare the result of floating point arithmetic.
Number Matchers Cheat Sheet
Every numeric comparison matcher Jest provides.
Matcher
Checks
.toBeGreaterThan(x)
received > x
.toBeGreaterThanOrEqual(x)
received >= x
.toBeLessThan(x)
received < x
.toBeLessThanOrEqual(x)
received <= x
.toBeCloseTo(x, digits?)
Floating point comparison within precision
.toBeNaN()
received is NaN
Why Floating Point Equality Fails
JavaScript numbers use the IEEE 754 double-precision format, which cannot represent every decimal fraction exactly. Arithmetic like 0.1 + 0.2 produces 0.30000000000000004, not 0.3. Testing this with .toBe(0.3) will fail even though the math is "correct" in practical terms.
Combine two range matchers with separate expect() calls (or use .toBeGreaterThanOrEqual() and .toBeLessThanOrEqual() together) to assert that a computed value falls within an acceptable range, which is common when testing things like percentages, scores, or randomized values.
Using .toBe() to compare floating point arithmetic results.
Forgetting .toBeCloseTo() accepts a precision argument for tighter or looser comparisons.
Writing expect(value > 10).toBe(true) instead of the more readable .toBeGreaterThan(10).
Not testing boundary values (exactly equal) when using strict vs. inclusive range matchers.
Key Takeaways
Range matchers (.toBeGreaterThan(), etc.) mirror standard comparison operators.
Always use .toBeCloseTo() instead of .toBe() for floating point arithmetic results.
.toBeCloseTo() accepts an optional precision argument for controlling tolerance.
Combining range matchers is a clean way to assert a value falls within bounds.
Pro Tip
Any time you see a decimal number in a test involving addition, subtraction, division, or multiplication, default to .toBeCloseTo() — it costs nothing when the math happens to be exact, and saves you from a flaky test when it isn't.
You now know how to safely compare numbers in Jest tests. Next, learn matchers for testing strings and patterns.