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(); });
Tests
.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); });
Tests
.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); });
Tests
.toChangeTo(checker, to)
Use .toChangeTo
when checking if the callback function mutates a piece of state to a target value.
test('passes when ', () => { let value = 1; expect(() => value = 10).toChangeTo(() => value, 10); });
Tests
.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$/); });
Tests
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/); });
Tests