The Jest Extended Library

Learn about jest-extended, an open-source library that easily extends our testing toolkit.

Expanding our testing toolkit

In addition to the variety of matchers provided to us directly from Jest, there are a number of libraries that extend its functionality with additional matchers. One of the most common is the jest-extended jest-extended library, created and maintained by the Jest community. It includes TypeScript support and extends functionality for asserting upon the following:

  • Arrays
  • Booleans
  • Dates
  • Functions
  • Mocks
  • Numbers
  • Objects
  • Promises
  • Strings
  • Symbols

We don’t necessarily get new functionality here, so it won’t make Jest do anything that it couldn’t have done before. What it does, though, is create incredible readability and clarity in our tests while removing the burden of crafting the correct assertions for our needs.

Extending expect

Jest’s expect function has to be extended in order to make these new matchers available for use. We can do this in one of the two ways discussed below.

Inside our test setup file, we can either extend some or all of these new matchers. To extend all matchers from the library, we can add the following lines of code:

import * as matchers from 'jest-extended';
expect.extend(matchers);

To extend only the selected matchers, we can extend them by adding the following lines of code:

import { toBeAfter, toSatisfy, toReject } from 'jest-extended';
expect.extend({ toBeAfter, toSatisfy, toReject });

The preferred method, however, is to automatically extend all matchers via the "jest" field in our package.json.

"jest": {
  "setupFilesAfterEnv": ["jest-extended/all"]
}

The API

It’s a good idea to read through the complete list of available matchers in the documentation. With options like .toSatisfy(), which works with custom predicates, .toBeBetween() for dates, and .toContainAllKeys() for objects, this library really allows us to be specific and explicit about what exactly we are testing.

You can try some of them out below:

Get hands-on with 1200+ tech skills courses.