Using Matchers

Jest uses “matchers” to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

Common Matchers

The simplest way to test a value is with exact equality.

  1. test('two plus two is four', () => {
  2. expect(2 + 2).toBe(4);
  3. });

In this code, expect(2 + 2) returns an “expectation” object. You typically won’t do much with these expectation objects except call matchers on them. In this code, .toBe(4) is the matcher. When Jest runs, it tracks all the failing matchers so that it can print out nice error messages for you.

toBe uses Object.is to test exact equality. If you want to check the value of an object, use toEqual:

  1. test('object assignment', () => {
  2. const data = {one: 1};
  3. data['two'] = 2;
  4. expect(data).toEqual({one: 1, two: 2});
  5. });

toEqual recursively checks every field of an object or array.

Using Matchers - 图1tip

toEqual ignores object keys with undefined properties, undefined array items, array sparseness, or object type mismatch. To take these into account use toStrictEqual instead.

You can also test for the opposite of a matcher using not:

  1. test('adding positive numbers is not zero', () => {
  2. for (let a = 1; a < 10; a++) {
  3. for (let b = 1; b < 10; b++) {
  4. expect(a + b).not.toBe(0);
  5. }
  6. }
  7. });

Truthiness

In tests, you sometimes need to distinguish between undefined, null, and false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.

  • toBeNull matches only null
  • toBeUndefined matches only undefined
  • toBeDefined is the opposite of toBeUndefined
  • toBeTruthy matches anything that an if statement treats as true
  • toBeFalsy matches anything that an if statement treats as false

For example:

  1. test('null', () => {
  2. const n = null;
  3. expect(n).toBeNull();
  4. expect(n).toBeDefined();
  5. expect(n).not.toBeUndefined();
  6. expect(n).not.toBeTruthy();
  7. expect(n).toBeFalsy();
  8. });
  9. test('zero', () => {
  10. const z = 0;
  11. expect(z).not.toBeNull();
  12. expect(z).toBeDefined();
  13. expect(z).not.toBeUndefined();
  14. expect(z).not.toBeTruthy();
  15. expect(z).toBeFalsy();
  16. });

You should use the matcher that most precisely corresponds to what you want your code to be doing.

Numbers

Most ways of comparing numbers have matcher equivalents.

  1. test('two plus two', () => {
  2. const value = 2 + 2;
  3. expect(value).toBeGreaterThan(3);
  4. expect(value).toBeGreaterThanOrEqual(3.5);
  5. expect(value).toBeLessThan(5);
  6. expect(value).toBeLessThanOrEqual(4.5);
  7. // toBe and toEqual are equivalent for numbers
  8. expect(value).toBe(4);
  9. expect(value).toEqual(4);
  10. });

For floating point equality, use toBeCloseTo instead of toEqual, because you don’t want a test to depend on a tiny rounding error.

  1. test('adding floating point numbers', () => {
  2. const value = 0.1 + 0.2;
  3. //expect(value).toBe(0.3); This won't work because of rounding error
  4. expect(value).toBeCloseTo(0.3); // This works.
  5. });

Strings

You can check strings against regular expressions with toMatch:

  1. test('there is no I in team', () => {
  2. expect('team').not.toMatch(/I/);
  3. });
  4. test('but there is a "stop" in Christoph', () => {
  5. expect('Christoph').toMatch(/stop/);
  6. });

Arrays and iterables

You can check if an array or iterable contains a particular item using toContain:

  1. const shoppingList = [
  2. 'diapers',
  3. 'kleenex',
  4. 'trash bags',
  5. 'paper towels',
  6. 'milk',
  7. ];
  8. test('the shopping list has milk on it', () => {
  9. expect(shoppingList).toContain('milk');
  10. expect(new Set(shoppingList)).toContain('milk');
  11. });

Exceptions

If you want to test whether a particular function throws an error when it’s called, use toThrow.

  1. function compileAndroidCode() {
  2. throw new Error('you are using the wrong JDK!');
  3. }
  4. test('compiling android goes as expected', () => {
  5. expect(() => compileAndroidCode()).toThrow();
  6. expect(() => compileAndroidCode()).toThrow(Error);
  7. // You can also use a string that must be contained in the error message or a regexp
  8. expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
  9. expect(() => compileAndroidCode()).toThrow(/JDK/);
  10. // Or you can match an exact error message using a regexp like below
  11. expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails
  12. expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass
  13. });

Using Matchers - 图2tip

The function that throws an exception needs to be invoked within a wrapping function otherwise the toThrow assertion will fail.

And More

This is just a taste. For a complete list of matchers, check out the reference docs.

Once you’ve learned about the matchers that are available, a good next step is to check out how Jest lets you test asynchronous code.