Skip to main content

Function

.toBeFunction()

Use .toBeFunction when checking if a value is a Function.

test('passes when value is a function', () => {
function noop() {}
expect(() => {}).toBeFunction();
expect(noop).toBeFunction();
expect(true).not.toBeFunction();
});

Open browser consoleTests

.toChange(checker)

Use .toChange when checking if the callback function mutates a piece of state that is queried by the checker function.

test('passes when given a value that the mutator increments', () => {
let value = 0;
expect(() => value++).toChange(() => value);
});

Open browser consoleTests

.toChangeBy(checker, by)

Use .toChangeBy when checking if the callback function mutates a piece of state by a specific amount.

test('passes when given a value that the mutator decrements', () => {
let value = 1;
expect(() => value--).toChangeBy(() => value, -1);
});

Open browser consoleTests

.toChangeTo(checker, to)

Use .toChangeTo when checking if the callback function mutates a piece of state to a target value.

test('passes when the value being checked becomes the provided value', () => {
let value = 1;
expect(() => value = 10).toChangeTo(() => value, 10);
});

Open browser consoleTests

.toThrowWithMessage(type, message)

Use .toThrowWithMessage when checking if a callback function throws an error with a given error type and given error message. Message can either be a String or a RegExp.

test('throws an error of type TypeError with message "hello world"', () => {
expect(() => {
  throw TypeError('hello world');
}).toThrowWithMessage(TypeError, 'hello world');

expect(() => {
  throw TypeError('hello world');
}).toThrowWithMessage(TypeError, /hello world/);

expect(() => {
  throw TypeError('hello world 2');
}).not.toThrowWithMessage(TypeError, 'hello world');

expect(() => {
  throw TypeError('hello world 2');
}).not.toThrowWithMessage(TypeError, /^hello world$/);

});

Open browser consoleTests

This works for promise rejections too.

test('throws an error of type TypeError with message "hello world"', async () => {
await expect(Promise.reject(new TypeError('hello world async'))).rejects.toThrowWithMessage(TypeError, /hello world/);
});

Open browser consoleTests