DEV Community

Cover image for Jest Tutorial For Beginners: Jest Matchers [2/4]
ABIDULLAH786
ABIDULLAH786

Posted on • Updated on

Jest Tutorial For Beginners: Jest Matchers [2/4]

Introduction

Jest uses "matchers" to let you test values in different ways.
Most of the information in this part is taken from the Jest docs.

Common Matchers

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

test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});
Enter fullscreen mode Exit fullscreen mode

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 to test exact equality. If you want to check the value of an object, use toEqual instead:

test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});
});
Enter fullscreen mode Exit fullscreen mode

toEqual recursively checks every field of an object or array.

You can also test for the opposite of a matcher:

test('adding positive numbers is not zero', () => {
  for (let a = 1; a < 10; a++) {
    for (let b = 1; b < 10; b++) {
      expect(a + b).not.toBe(0);
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

1. Truthiness

In tests, you sometimes need to distinguish between undefined, null, and false. 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:
test('null', () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});

test('zero', () => {
  const z = 0;
  expect(z).not.toBeNull();
  expect(z).toBeDefined();
  expect(z).not.toBeUndefined();
  expect(z).not.toBeTruthy();
  expect(z).toBeFalsy();
});
Enter fullscreen mode Exit fullscreen mode

Note: use matcher that most precisely corresponds to what you want your code to be doing.

2. Numbers

The jest provides different matchers for comparing numbers.
Example:

test('two plus two', () => {
  const value = 2 + 2;
  expect(value).toBeGreaterThan(3);
  expect(value).toBeGreaterThanOrEqual(3.5);
  expect(value).toBeLessThan(5);
  expect(value).toBeLessThanOrEqual(4.5);

  // toBe and toEqual are equivalent for numbers
  expect(value).toBe(4);
  expect(value).toEqual(4);
});
Enter fullscreen mode Exit fullscreen mode

For floating-point equality, use toBeCloseTo instead of toEqual, because you don't want a test to depend on a tiny rounding error to understand this error click here.

test('adding floating point numbers', () => {
  const value = 0.1 + 0.2;
  //expect(value).toBe(0.3);           This won't work because of rounding error
  expect(value).toBeCloseTo(0.3); // This works.
});
Enter fullscreen mode Exit fullscreen mode

2. Strings

jest provides the facility to check strings against regular expressions with toMatch:

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});
Enter fullscreen mode Exit fullscreen mode

3. Arrays and iterables

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

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'milk',
];

test('the shopping list has milk on it', () => {
  expect(shoppingList).toContain('milk');
  expect(new Set(shoppingList)).toContain('milk');
});
Enter fullscreen mode Exit fullscreen mode

4. Exceptions

If you want to test whether a particular function throws an error when it's called, the jest provides the matcher toThrow.

function compileAndroidCode() {
  throw new Error('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
  expect(() => compileAndroidCode()).toThrow();
  expect(() => compileAndroidCode()).toThrow(Error);

  // You can also use the exact error message or a regexp
  expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
  expect(() => compileAndroidCode()).toThrow(/JDK/);
});
Enter fullscreen mode Exit fullscreen mode

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


Exploring new concepts and sharing them with others is my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!

Connect me on Twitter, Linkedin and GitHub

As you know that everyone has a room to improve, so your suggestion is appreciated. And I would love (❤️) to know something new.

Latest comments (0)