Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 30 ยท Matchers

Common Matchers

Learn the everyday Jest matchers: toBe versus toEqual versus toStrictEqual, truthiness matchers like toBeNull and toBeDefined, and how not flips any check.

A matcher is the part of an assertion that says what you expect. In expect(total).toBe(30), the call to expect hands Jest the actual value and toBe is the matcher. Jest ships dozens of matchers. A handful of them cover most real tests, and the biggest source of confusion is choosing between three that look alike: toBe, toEqual and toStrictEqual.

This lesson covers those three, the truthiness family, and .not. Numbers, strings, arrays, objects and errors get their own lessons right after.

Real versus stand-in. The Jest snippets below are real and read-only. The TryIt blocks contain a stand-in expect that implements these matchers with the same documented rules (Object.is for toBe, recursive comparison for toEqual, stricter comparison for toStrictEqual). It is not Jest's source, and Jest handles many more cases such as sparse arrays, Map and Set.

toBe: exact identity

toBe compares with Object.is. For numbers, strings, booleans, null and undefined that is plain equality. For objects and arrays it means the same object in memory, not "looks the same".

JavaScript
test("toBe on primitives", () => {
  expect(2 + 2).toBe(4);
  expect("jest").toBe("jest");
  expect(true).toBe(true);
});

test("toBe on objects compares identity", () => {
  const a = { id: 1 };
  const b = { id: 1 };
  expect(a).toBe(a);   // passes: same object
  expect(a).toBe(b);   // FAILS: two different objects
});

Never use toBe to compare two arrays or objects that were built separately. It fails even when the contents are identical, and the message ("serializes to the same string") will remind you to use toEqual.

Because toBe uses Object.is, two quirks show up: Object.is(NaN, NaN) is true (so expect(NaN).toBe(NaN) passes), and Object.is(0, -0) is false.

toEqual: same contents

toEqual compares values recursively. It looks inside objects and arrays and checks that all the data matches, regardless of identity.

JavaScript
test("toEqual compares contents", () => {
  expect({ id: 1, tags: ["a", "b"] }).toEqual({ id: 1, tags: ["a", "b"] });
  expect([1, [2, 3]]).toEqual([1, [2, 3]]);
});

Its rules are relaxed in a few ways that matter:

  • A property whose value is undefined is ignored, so { a: 1, b: undefined } equals { a: 1 }.
  • It does not check the object's type or class, so a class instance with the right fields equals a plain object with the same fields.
  • Arrays with holes are treated like arrays containing undefined.

toStrictEqual: same contents and same shape

toStrictEqual is toEqual with the loopholes closed:

  • Keys with undefined values count. { a: 1, b: undefined } does not strictly equal { a: 1 }.
  • Object types are checked: an instance of a class does not strictly equal a plain object with the same fields.
  • Sparse arrays (with holes) are different from arrays with explicit undefined.
JavaScript
class Point {
  constructor(x, y) { this.x = x; this.y = y; }
}

test("class instance versus plain object", () => {
  expect(new Point(1, 2)).toEqual({ x: 1, y: 2 });          // passes
  expect(new Point(1, 2)).not.toStrictEqual({ x: 1, y: 2 }); // different types
});

Which should you use? Prefer toEqual for everyday data checks, because a stray undefined property is usually not a behavior you care about. Reach for toStrictEqual when the exact shape is the point, such as the output of a serializer or API response mapper where an extra undefined key would leak into JSON.

Which equality matcher?

toBe Same value or same object. Uses Object.is.
toEqual Same contents, recursively. Ignores undefined keys.
toStrictEqual Same contents, keys and type.

Primitives use toBe. Objects and arrays use toEqual by default.

1 / 2

Try the three side by side

The stand-in below implements all three. Each line prints whether the check passes. Read the results, predict the ones you are unsure about before running, then edit values to test your understanding.

JS toBe, toEqual and toStrictEqual

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

No output.

You should see toBe fail for the two equal-looking objects while toEqual passes, and the two strict checks fail where the relaxed ones passed. The last two lines show the Object.is quirks: NaN equals itself, but 0 and -0 are different.

Truthiness matchers

Sometimes you do not care about an exact value, only whether it is "something" or "nothing". Jest has matchers for each case:

Matcher Passes when
toBeNull() the value is exactly null
toBeUndefined() the value is exactly undefined
toBeDefined() the value is anything except undefined
toBeTruthy() the value is truthy in an if
toBeFalsy() the value is falsy in an if (false, 0, "", null, undefined, NaN)
toBeNaN() the value is NaN
JavaScript
test("null is falsy but not undefined", () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).toBeFalsy();
  expect(n).not.toBeTruthy();
});

test("zero is falsy but still defined", () => {
  const z = 0;
  expect(z).not.toBeNull();
  expect(z).toBeDefined();
  expect(z).toBeFalsy();
});

Be specific when you can. toBeTruthy() passes for 1, "x", [] and {}, so it is a weak check. If a function should return true, write toBe(true). Use the truthiness matchers when you really only care about presence, for example "a user was found" with toBeTruthy() or "nothing was found" with toBeNull().

not: flip any matcher

Put .not before a matcher to invert it.

JavaScript
expect(4).not.toBe(5);
expect([1, 2]).not.toEqual([2, 1]);
expect(user.middleName).not.toBeDefined();

Use not for things that must not happen, such as a secret field missing from a response. Do not use it as a shortcut for "anything but the broken result". expect(total).not.toBe(0) passes for -5, NaN and "hello" too. Whenever you can, assert the precise value instead.

JS Truthiness and not

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

No output.

Notice expect([]).toBeTruthy() passes. An empty array is truthy in JavaScript, which is why toBeTruthy is often too weak to catch a bug.

Reading matcher failures

Every matcher prints a message that names itself. For toEqual on objects, Jest prints a colored diff with - lines for expected and + lines for received, so you can see exactly which property differs. Spend time reading that diff; it usually points straight at the bug.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. const a = { id: 1 }; const b = { id: 1 }; Which assertion passes?

    toBe uses Object.is, so two separate objects are different. toEqual compares contents and passes.
  2. 2. What is the difference between toEqual and toStrictEqual for { a: 1, b: undefined } and { a: 1 }?

    toEqual ignores properties whose value is undefined. toStrictEqual treats the extra key as a difference.
  3. 3. Which value makes expect(value).toBeFalsy() fail?

    An empty array is truthy in JavaScript. 0, the empty string and null are all falsy.
  4. 4. Why is expect(total).not.toBe(0) a weak assertion?

    Negative checks accept a huge set of values. Assert the exact expected value when you know it.

Summary

  • toBe uses Object.is: great for primitives, identity-only for objects.
  • toEqual compares contents recursively and ignores undefined properties and object types.
  • toStrictEqual also checks undefined keys, sparse arrays and types.
  • toBeNull, toBeUndefined, toBeDefined, toBeTruthy, toBeFalsy and toBeNaN describe presence or absence; prefer an exact matcher when you know the value.
  • .not inverts any matcher, but a precise positive assertion is usually stronger.

Next: Numbers and Strings.