Common Matchers in Jest
18 min read·Jan 1, 2025
In Jest, matchers are methods used in assertions to check the expected output of a test against the actual result.
They provide a variety of ways to validate values, such as equality, truthiness, or specific content, enabling precise and readable test expectations.
Testing primitive values
To check the strict equality of primitive values or the referential identity of object instances, you can use the toBe() matcher:
expect(primitive).toBe(value);
Where value is a primitive value, such as a string, a number, etc.
Example
In this example, the toBe() matcher is used to check the value of the name and age properties of the user object:
const user = {
name: 'John Doe',
age: 30
};
expect(user.name).toBe('John Doe');
expect(user.age).toBe(30);
Matching string patterns with regular expressions
To check whether a string matches a regular expression pattern, you can use the toMatch() matcher:
expect(string).toMatch(regex);
Where regex is a regular expression.
Example
In this example, the toMatch() matcher is used to verify that the email variable contains a valid email address using a regular expression:
const email = 'john5@mail.com';
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
expect(email).toMatch(emailRegex);
Comparing numbers
To compare whether a number is greater or less than another number, you can use the toBeGreaterThan() and toBeLessThan() matchers:
expect(number).toBeGreaterThan(value);
expect(number).toBeLessThan(value);
Where value is either an integer or a floating-point.
On the other hand, to compare whether an integer is greater than or equal to, or less than or equal to another integer, you can use the toBeGreaterThanOrEqual() and toBeLessThanOrEqual() matchers:
expect(number).toBeGreaterThanOrEqual(value);
expect(number).toBeLessThanOrEqual(value);
Where value is an integer.
Note: These last two matchers are not recommended to compare floating-point values as explained below.
Example
In this example, the toBeGreaterThan(), toBeLessThan(), toBeGreaterThanOrEqual(), and toBeLessThanOrEqual() matchers are used to compare the result of the multiplication of two integers:
const result = 4 * 3;
expect(result).toBeGreaterThan(10);
expect(result).toBeLessThan(14);
expect(result).toBeGreaterThanOrEqual(12);
expect(result).toBeLessThanOrEqual(12);
Comparing floating-point numbers
To check whether two floating-point numbers are approximately equal, you can use the toBeCloseTo() matcher, as the toBe() matcher will fail due to the fact that arithmetic on decimal values often have rounding errors:
expect(float).toBeCloseTo(value);
Where value is a floating-point.
Example
In this example, comparing two floating-point numbers using the toBe() matcher will fail:
expect(0.1 + 0.2).toBe(0.3);
Whereas, in this example, comparing the same numbers using the toBeCloseTo() matcher will pass:
expect(0.1 + 0.2).toBeCloseTo(0.3);
Checking the existence of values
To check whether a value is undefined or null, you can use the toBeUndefined() and toBeNull() matchers:
expect(value).toBeUndefined();
expect(value).toBeNull();
On the other hand, to check whether a value is not undefined, you can use the toBeDefined() matcher or the not.toBe(undefined):
expect(value).toBeDefined();
expect(value).not.toBe(undefined);
Example
In this example, the toBeUndefined() matcher is used to check the value the user variable that was declared but not initialized:
let user;
expect(user).toBeUndefined();
In this example, the toBeNull() matcher is used to check the value the user variable was initialized with the null value:
let user = null;
expect(user).toBeNull();
In this example, the toBeDefined() matcher is used to check whether the user variable was initialized:
let user = {};
expect(user).toBeDefined();
expect(user).not.toBe(undefined);
Checking the deep equality of arrays and objects
To recursively compare every property of nested structures, such as objects and arrays, you can use the toEqual() matcher:
expect(object).toEqual(value);
Where value is either an array or an object.
Example
In this example, the toEqual() matcher is used to check whether the properties of the user object and its copy are identical:
const user = {
name: 'John Doe',
contact: {
address: {
street: '1 Hacker Way',
city: 'Menlo Park',
country: 'USA'
},
emails: ['john5@mail.com']
}
};
const copy = { ...user };
expect(user).toEqual(copy);
Checking the existence of array elements
To check whether an array contains a value, you can use the toContain() matcher:
expect(array).toContain(value);
Example
In this example, the toContain() matcher is used to check whether the "john5@mail.com" string exist in the emails array:
const emails = [
'jackjones@mail.com',
'alice.doe@mail.com',
'john5@mail.com'
];
expect(emails).toContain('john5@mail.com');
Checking the existence of object properties
To check whether an object has a property, you can use the toHaveProperty() matcher:
expect(object).toHaveProperty(path, value?);
Where:
pathis a string describing the path to the (nested) target property in the dot notation format.value?is an optional value used to compare the property's value.
Note that if the value is not provided, the toHaveProperty() will only check the existence of the property.
Example
In this example, the toHaveProperty() matcher is used to first check if the contact.address.street property exists in the user object and then if its value equals the "1 Hacker Way" string:
const user = {
name: 'John Doe',
contact: {
address: {
street: '1 Hacker Way',
city: 'Menlo Park',
country: 'USA'
}
}
};
expect(user).toHaveProperty('contact.address.street');
expect(user).toHaveProperty('contact.address.street', '1 Hacker Way');
Checking the truthiness of expressions
To check whether an expression is truthy or falsy, you can use the toBeTruthy() or toBeFalsy() matchers:
expect(expression).toBeTruthy();
expect(expression).toBeFalsy();
Example
In this example, the toBeTruthy() matcher is used to check whether the value of the email variable is truthy:
let email = 'john5@mail.com'
expect(email).toBeTruthy();
In this example, the toBeTruthy() matcher is used to check whether the value of the uninitialized password variable is falsy:
let password;
expect(password).toBeFalsy();
Checking exception types and error messages
To check if a function throws an exception, you can use the toThrow(error?) matcher as follows:
expect(() => fn()).toThrow(error?)
Where:
-
fnis a function. -
error?is an optional error class or error message.
Note: The function that throws an exception needs to be invoked within a wrapping function otherwise the
toThrow()matcher will fail.
Example
In this example, the toThrow() matcher is used to check whether the throwError function throws, the thrown error is instantiated from the Error class, and the error message equals to the "invalid_email_address" string:
function throwError() {
throw new Error('invalid_email_address');
}
it('should throw an error', () => {
expect(() => throwError()).toThrow();
expect(() => throwError()).toThrow(Error);
expect(() => throwError()).toThrow('invalid_email_address');
});
Summary
Here's a summary of what you've learned in this lesson:
toBe(value)is used to compare primitive values.toMatch(regex)is used to match a string to a regular expression.toBeGreaterThan(value)is used to check if a number is greater than another one.toBeLessThan(value)is used to check if a number is less than another one.toBeGreaterThanOrEqual(value)is used to check if an integer is greater than or equal to another integer.toBeLessThanOrEqual(value)is used to check if an integer is less than or equal to another one.toBeCloseTo(value)is used to check if a floating-point is relatively equal to another one.toBeUndefined()is used to check if a value isundefined.toBeNull()is used to check if a value isnull.toBeDefined()is used to check if a value is notundefined.not.toBe(undefined)is used to check if a value is notundefined.toEqual(value)is used to check the deep equality of arrays and objects.toContain(value)is used to check if an array contains an element.toHaveProperty(path, value?)is used to check if an object has a property.toBeTruthy()is used to check if an expression is truthy.toBeFalsy()is used to check if an expression is falsy.toThrow(error?)is used to check if a function throws an error.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery