Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 30 ยท Matchers

Numbers and Strings

Use Jest's number and string matchers: toBeGreaterThan, toBeCloseTo for floating point, toMatch with regex, toContain and toHaveLength, with runnable stand-ins.

Numbers and strings are everywhere in tests: prices, counts, durations, error messages, formatted dates. Jest has matchers made for them, and one of those matchers solves a problem that surprises every beginner: 0.1 + 0.2 is not 0.3.

This lesson covers comparison matchers, toBeCloseTo, toMatch, toContain and toHaveLength. It builds on Common Matchers.

Real versus stand-in. The Jest snippets are real and read-only. The TryIt blocks implement the same matchers in a few lines of plain JavaScript so you can see the rules at work. Real Jest also supports BigInt, richer failure messages and more types.

Comparing numbers

For exact integers toBe is fine. For ranges, use the comparison matchers:

JavaScript
test("comparison matchers", () => {
  const items = 7;
  expect(items).toBeGreaterThan(3);
  expect(items).toBeGreaterThanOrEqual(7);
  expect(items).toBeLessThan(10);
  expect(items).toBeLessThanOrEqual(7);
});

They are the natural choice when the exact number does not matter, for example "the request took less than 200 ms", "the list has more than zero results" or "the id is positive". Avoid asserting on something that is naturally varying with an exact number; assert a range instead.

The floating-point trap and toBeCloseTo

JavaScript numbers are binary floating-point values, and many decimals cannot be stored exactly:

JavaScript
test("this fails!", () => {
  expect(0.1 + 0.2).toBe(0.3);
  // Expected: 0.3
  // Received: 0.30000000000000004
});

toBeCloseTo(expected, numDigits) fixes that. It passes when the difference is smaller than half of the last decimal place you ask for. The default numDigits is 2.

JavaScript
test("floating point, done right", () => {
  expect(0.1 + 0.2).toBeCloseTo(0.3);          // default: 2 digits
  expect(0.1 + 0.2).toBeCloseTo(0.3, 10);      // stricter
  expect(3.14159).toBeCloseTo(3.14, 2);
  expect(3.14159).not.toBeCloseTo(3.14, 4);
});

The rule is |expected - received| < 10^(-numDigits) / 2. With 2 digits the allowed difference is 0.005, with 4 digits it is 0.00005. Use toBeCloseTo for any number that came from division, multiplication by a fraction, trigonometry, averages or money computed in floats. For money specifically, many teams store whole cents as integers so toBe stays exact.

Seeing the rule

JS Why toBeCloseTo exists

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

No output.

Look at the last two rows: 100 / 3 is about 33.3333. It is close to 33.33 with 2 digits, but not with 3, where the allowed difference shrinks to 0.0005.

Matching strings

For an exact string use toBe or toEqual. For partial checks there are three tools.

toMatch checks a string against a regular expression or a substring:

JavaScript
test("string patterns", () => {
  expect("Order #4821 shipped").toMatch(/#\d+/);
  expect("Order #4821 shipped").toMatch("shipped");   // substring
  expect("team").not.toMatch(/I/);
  expect("[email protected]").toMatch(/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i);
});

Remember that a string argument is a substring, not a regex. Regex checks are great for values with unpredictable parts such as ids, timestamps and tokens, where you assert the shape rather than the exact text.

toContain checks that a string contains a substring, or that an array contains an item (using ===):

JavaScript
expect("hello world").toContain("world");
expect(["red", "green", "blue"]).toContain("green");

toHaveLength checks the length property of strings, arrays and anything that has one:

JavaScript
expect("jest").toHaveLength(4);
expect([1, 2, 3]).toHaveLength(3);
expect([]).toHaveLength(0);

toHaveLength gives a better message than expect(list.length).toBe(3), because it prints the whole array when it fails. Matching objects inside arrays comes later, in Arrays and Objects.

Matching exact text safely

Exact text assertions are brittle when the message changes slightly. A mix of precision levels works best:

  • Assert exact text for fixed, user-facing strings that are part of the contract (an error message that the UI shows).
  • Assert a pattern for generated parts (ids, dates).
  • Assert contains for long text where only a key phrase matters.
JavaScript
test("welcome email", () => {
  const body = renderWelcome({ name: "Ada", plan: "Pro" });
  expect(body).toContain("Hi Ada");           // key phrase
  expect(body).toMatch(/Pro plan/);           // key phrase
  expect(body).not.toMatch(/undefined|null/); // template bugs
});

That last check is a cheap guard that catches the classic "Hello undefined" bug.

Strings and numbers together

This stand-in implements toMatch, toContain, toHaveLength and the comparisons, then runs a small report-building function through them.

JS Matchers on strings and numbers

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

No output.

Common pitfalls

  • Comparing floats with toBe or toEqual. Use toBeCloseTo. It also works on numbers inside objects when you check them one by one, because toEqual has no tolerance.
  • Passing a regex where you wanted a literal. toMatch("1.5") is a substring check, and toMatch(/1.5/) treats the dot as "any character".
  • toContain on an array of objects. It uses ===, so toContain({ id: 1 }) fails even when an equal object is present. Use toContainEqual, covered in the arrays lesson.
  • Using toHaveLength on something without length. A number or undefined throws a clear error rather than failing quietly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does expect(0.1 + 0.2).toBe(0.3) fail?

    Binary floating point cannot store 0.1 and 0.2 exactly, so the sum is slightly off. Use toBeCloseTo.
  2. 2. With toBeCloseTo(expected, 2), what difference is allowed?

    The rule is a difference below 10^(-digits) / 2, which is 0.005 for 2 digits.
  3. 3. What does expect('abc').toMatch('b.') check?

    A string argument to toMatch is a substring check. Pass /b./ if you want a regular expression.
  4. 4. Which assertion is best for confirming a list has exactly three items?

    toHaveLength checks the length and prints the whole list when it fails.

Summary

  • Use toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan and toBeLessThanOrEqual for ranges.
  • Use toBeCloseTo(value, digits) for floating-point results; the allowed difference is 10^-digits / 2.
  • toMatch takes a regex or a substring; use patterns for generated text and exact text for fixed contract strings.
  • toContain checks substrings and array items by ===; toHaveLength checks length.
  • Guard against template bugs with not.toMatch(/undefined|null/).

Next: Arrays and Objects.