Skip to content

Matcher documentation

Raphael Luba edited this page Oct 28, 2015 · 8 revisions

About this documentation

All examples expect hamjest to be available as __.

Many matchers take valueOrMatcher as an argument. If you provide a value that is not a matcher, it will be wrapped with __.equalTo(...).

General matchers

truthy()

Matches truthy values:

__.assertThat({}, __.is(__.truthy())); // Passes
__.assertThat(25, __.is(__.truthy())); // Passes

__.assertThat(undefined, __.is(__.truthy())); // Fails
__.assertThat('', __.is(__.truthy())); // Fails

falsy(), falsey()

Matches falsy values:

__.assertThat(null, __.is(__.falsy())); // Passes
__.assertThat('', __.is(__.falsy())); // Passes

__.assertThat('Hello', __.is(__.falsy())); // Fails
__.assertThat(42, __.is(__.falsy())); // Fails

anything()

Matches everything. It's useful as a placeholder when implementing matchers that take optional sub-matchers (eg. throws, fulfilled, ...).

equalTo(value)

Performs a deep comparison between the given and the tested value. See _.isEqual for details.

__.assertThat(25, __.equalTo(25)); // Passes
__.assertThat(['A', 'B'], __.equalTo(['A', 'B'])); // Passes
__.assertThat({some: 'value'}, __.equalTo({some: 'value'})); // Passes

__.assertThat({other: 'value'}, __.equalTo({some: 'value'})); // Fails
__.assertThat('some value', __.equalTo({some: 'value'})); // Fails
__.assertThat(25, __.equalTo({some: 'value'})); // Fails

strictlyEqualTo(value)

Performs strict comparison (===) between the given and the tested value:

var anObj = {};
__.assertThat(anObj, __.strictlyEqualTo(anObj)); // Passes
__.assertThat(anObj, __.strictlyEqualTo({})); // Fails

is(valueOrMatcher)

Syntactic sugar for readable code and error descriptions. It wraps a valueOrMatcher and appends "is " to the description.

__.assertThat({some: 'value'}, __.equalTo({some: 'value'})); // Passes
__.assertThat({some: 'value'}, __.is(__.equalTo({some: 'value'}))); // Same as above
__.assertThat({some: 'value'}, __.is({some: 'value'})); // Same as above

not(valueOrMatcher)

Matches if the given matcher fails and vice versa. As usual, if the given value is not a matcher, it is wrapped with equalTo.

__.assertThat(6, __.is(__.not(5))); // Passes
__.assertThat(2, __.is(__.not(__.greaterThan(4)))); // Passes

__.assertThat(5, __.is(__.not(5))); // Fails
__.assertThat(5, __.is(__.not(__.greaterThan(4)))); // Fails

defined()

Matches everything except undefined:

__.assertThat('example', __.is(__.defined())); // Passes

__.assertThat(undefined, __.is(__.defined())); // Fails
var groundTruth;
__.assertThat(groundTruth, __.is(__.defined())); // Fails

undefined() / undef()

The opposite of defined().

String matchers

containsString(string)

Matches any string that contains the given string:

__.assertThat('great value', __.containsString('great')); // Passes

__.assertThat('good value', __.containsString('great')); // Fails

startsWith(string)

Matches any string that starts with the given string:

__.assertThat('the best player', __.startsWith('the best')); // Passes

__.assertThat('almost the best player', __.startsWith('the best')); // Fails

endsWith(string)

Matches any string that starts with the given string:

__.assertThat('King Ludwig', __.endsWith('Ludwig')); //Passes

__.assertThat('King Ludwig II', __.endsWith('Ludwig')); //Fails

matchesPattern(stringOrRegExp)

Matches any string that is matched by the given regular expression.

__.assertThat(username, __.matchesPattern('[a-z]+'));
__.assertThat(score, __.matchesPattern(/\d+/));

hasSize(valueOrMatcher)

Matches if the string has the given size or its size matches the given matcher:

__.assertThat('short', __.hasSize(5)); // Passes
__.assertThat('loooooooong', __.hasSize(__.greaterThan(8))); // Passes

__.assertThat('1234', __.hasSize(__.greaterThan(8))); // Fails

Can also be used for collections.

isEmpty()

Shorthand for hasSize(0) with concise description:

__.assertThat('', __.isEmpty()); // Passes

__.assertThat('X', __.isEmpty()); // Fails

Can also be used for collections.

(Available since v2.11.0)

Number matchers

lessThan(number), lessThanOrEqualTo(number), greaterThan(number), greaterThanOrEqualTo(number)

Use <, <=, > and >= respectively to compare the test value to the given value.

__.assertThat(5, __.greaterThanOrEqualTo(5)); // Passes

__.assertThat(4, __.lessThan(4)); // Fails

closeTo(number, delta)

Matches any number that is between number - delta and number + delta. Useful for matching floating point numbers.

__.assertThat(1/3, __.closeTo(0.33, 0.01)); // Passes

__.assertThat(actual, __.closeTo(expected, 0.001));

Date matchers

before(date), beforeOrEqualTo(date), after(date), afterOrEqualTo(date)

Use <, <=, > and >= respectively to compare the test date to the given date.

__.assertThat(new Date('2015-06-17T14:00:00'), __.after(new Date('2015-06-01T00:00:00'))); // Passes

__.assertThat(new Date('2015-06-17T14:00:00'), __.after(new Date('2015-06-17T15:00:00'))); // Fails

(Available since v2.9.0)

Collection matchers

Collection matchers can be applied to arrays and objects.

everyItem(valueOrMatcher)

Matches if the given matcher or value matches every item in the collection:

__.assertThat([1, 2, 3], __.everyItem(__.is(__.number()))); // Passes
__.assertThat({math: 'A', drawing: 'A'}, __.everyItem('A'))); // Passes
__.assertThat({math: 'A', drawing: 'A'}, __.everyItem(__.is('A')))); // Same as above

__.assertThat([1, '2', 3], __.everyItem(__.is(__.number()))); // Fails

hasSize(valueOrMatcher)

Matches if the collection has the given size or its size matches the given matcher:

__.assertThat([1, 2, 3, 4, 5], __.hasSize(5)); // Passes
__.assertThat({some: 'value'}, __.hasSize(__.lessThan(3))); // Passes

__.assertThat([], __.hasSize(__.greaterThan(8))); // Fails

Uses _.size internally. Can also be used for strings.

isEmpty()

Shorthand for hasSize(0) with concise description:

__.assertThat([], __.isEmpty()); // Passes
__.assertThat({}, __.isEmpty()); // Passes

__.assertThat([''], __.isEmpty()); // Fails
__.assertThat({with: 'a property'}, __.isEmpty()); // Fails

Can also be used for strings.

(Available since v2.11.0)

Array matchers

hasItem(valueOrMatcher)

Matches any array that contains at least one item that matches the given matcher (or value):

__.assertThat([5, 7, 10], __.hasItem(7)); // Passes
__.assertThat([5, 7, 10], __.hasItem(__.greaterThan(8))); // Passes

__.assertThat([5, 7, 10], __.hasItem(__.lessThan(3))); // Fails

hasItems(valuesOrMatchers...)

Matches if every given value or matcher matches at least one item in the tested array. Additional items in the array are ignored.

__.assertThat([5, 7, 10], __.hasItems(10, 7)); // Passes
__.assertThat([5, 7, 10], __.hasItems(10, __.greaterThan(8))); // Passes, both conditions satisfied by '10'.

__.assertThat([5, 7, 10], __.hasItems(7, 8)); // Fails
__.assertThat([5, 7, 10], __.hasItems(__.lessThan(5), __.greaterThan(8))); // Fails

contains(valuesOrMatchers...)

Matches if the values in the tested array match exactly the given matcher sequence, i.e. the first matcher matches the first item, the second matcher matches the second item, etc.

__.assertThat([5, 7, 10], __.contains(5, 7, 10)); // Passes
__.assertThat([5, 7, 10], __.contains(__.lessThan(7), 7, __.greaterThan(2))); // Passes

__.assertThat([5, 10, 7], __.contains(5, 7, 10)); // Fails
__.assertThat([5, 7, 10, 11], __.contains(__.lessThan(7), 7, __.greaterThan(2))); // Fails because there's no value or matcher for '11'
__.assertThat([5, 7], __.contains(__.lessThan(7), 7, __.greaterThan(2))); // Fails because there are only two items in the array but three matchers

containsInAnyOrder(valuesOrMatchers...)

Matches if every value in the tested array is matched by exactly one given matcher or value:

__.assertThat([5, 7, 10], __.containsInAnyOrder(5, 7, 10)); // Passes
__.assertThat([5, 10, 7], __.containsInAnyOrder(5, 7, 10)); // Passes
__.assertThat([5, 10, 7], __.containsInAnyOrder(__.lessThan(7), 7, __.greaterThan(7))); // Passes

__.assertThat([5, 10, 7, 6], __.containsInAnyOrder(__.lessThan(7), 7, __.greaterThan(7))); // Fails and describes that there's no matcher for '6'
__.assertThat([7, 10], __.containsInAnyOrder(__.lessThan(7), 7, __.greaterThan(7))); // Fails and describes that 'lessThan(7)' was not matched

Attention: This is matcher is currently not promise aware.

orderedBy(comparisonFunction, [orderName])

Matches if the tested array is ordered by the relation defined by the given comparison function. The comparison function must have the form function (a, b) and should return true if a should precede b in the array. An optional order name can be provided as a second argument. If none is provided, the function name is used to describe the order.

__.assertThat([1, 2, 3], __.is(__.orderedBy(function (a, b) { return a < b; }, 'ascending'))); // Passes
__.assertThat([1, 2, 3], __.is(__.orderedBy(function ascending(a, b) { return a < b; }))); // Same as above
__.assertThat([3, 2, 1], __.is(__.orderedBy(function descending(a, b) { return a > b; }))); // Passes

__.assertThat([1, 3, 2], __.is(__.orderedBy(function ascending(a, b) { return a < b; }))); // Fails and describes that '3' and '2' are not in the desired order.

Object matchers

hasProperty(name, [valueOrMatcher])

Matches if the value has a property with the given name:

__.assertThat({name: 'jim', age: 25}, __.hasProperty('name')); // Passes

__.assertThat({firstName: 'jim'}, __.hasProperty('name')); // Fails

You can provide a valueOrMatcher to verify the property value:

__.assertThat({name: 'jim', age: 25}, __.hasProperty('name', 'jim')); // Passes
__.assertThat({name: 'jim'}, __.hasProperty('name', __.startsWith('j')); // Passes

__.assertThat({name: 'tom'}, __.hasProperty('name', __.startsWith('j')); // Fails

hasProperties({name: valueOrMatcher, name: valueOrMatcher, ...})

Matches if the value has all specified properties and if their corresponding values match. Additional properties are ignored.

__.assertThat({name: 'jim', age: 25}, __.hasProperties({name: 'jim',  age: 25})); // Passes
__.assertThat({name: 'jim', age: 25}, __.hasProperties({name: __.string(), age: __.greaterThan(18)})); // Passes
__.assertThat({name: 'jim', age: 25, height: 175}, __.hasProperties({name: __.string(), age: __.greaterThan(18)})); // Passes, height is ignored

__.assertThat({name: 'jim', age: 24}, __.hasProperties({name: 'jim',  age: 25})); // Fails
__.assertThat({name: 'jim', age: 17}, __.hasProperties({name: __.string(), age: __.greaterThan(18)})); // Fails
__.assertThat({name: 'jim'}, __.hasProperties({name: __.string(), age: __.greaterThan(18)})); // Fails

Failures provide a detailed description of all properties that did not match.

Function matchers

throws([matcherOrValue])

Assert that a function throws anything:

__.assertThat(function () {
...
}, __.throws());

Assert that a function thows a specific type:

__.assertThat(function () {
...
}, __.throws(__.instanceOf(AssertionError)));

Assert that a function does not throw anything:

__.assertThat(function () {
...
}, __.not(__.throws()));

returns([matcherOrValue])

Assert that a function returns anything (and does not throw):

__.assertThat(myFunction, __.returns());

Assert that a function returns a specific value:

__.assertThat(myFunction, __.returns("expected string value"));

Assert that a function returns a value using a matcher:

__.assertThat(myFunction, __.returns(__.containsString("expected"));

Assert that an object has a getter function that returns a specific value:

__.assertThat(customer, __.hasProperties({
    getAccountNumber: __.returns(__.number())
}));

(Available since v2.13.0)

Type matchers

array()

Matches any value that is an array:

__.assertThat([], __.is(__.array())); // Passes

__.assertThat({}, __.is(__.array())); // Fails
__.assertThat('no array', __.is(__.array())); // Fails

object()

Matches any value that is an object (see _.isObject for what is considered an object):

__.assertThat({}, __.is(__.object())); // Passes
__.assertThat([], __.is(__.object())); // Passes

__.assertThat('no object', __.is(__.object())); // Fails
__.assertThat('41', __.is(__.object())); // Fails

instanceOf(Type)

Matches if the value is of the given type:

__.assertThat(animal, __.is(__.instanceOf(Pony)));
__.assertThat(error, __.is(__.instanceOf(AssertionError)));

bool(), date(), func(), number(), regExp(), string()

Match values of the corresponding types (using _.isBoolean, _.isDate, _.isFunction, _.isNumber, _.isRegExp and _.isString respectively).

__.assertThat(playerName, __.is(__.string()));
__.assertThat(pattern, __.is(__.regExp()));

promise()

Matches any value that is recognized as a promise by Q's isPromiseAlike (i.e. anything that has a then function):

__.assertThat(Q(), __.is(__.promise())); // Passes

__.assertThat({}, __.is(__.promise())); // Fails

typedError(type, messageValueOrMatcher)

Most useful in combination with __.throws(…):

__.assertThat(myFunction, __.throws(__.typedError(RangeError, 'value out of range')));

(Available since v2.13.0)

Meta-matchers

matches(value)

Assert that a matcher matches a given value:

__. assertThat(__.containsString('value'), __.matches('some value'));

hasDescription(valueOrMatcher)

Assert that a matcher describes itself exactly like the given string:

__. assertThat(__.containsString('value'), __.hasDescription('a string containing "value"'));

Assert that a matcher's description contains a certain string:

__. assertThat(__.hasSize(5), __.hasDescription(__.containsString('with size <5>')));

failsToMatch(value, mismatchDescriptionValueOrMatcher)

Assert that a matcher does not match the given value and describes the mismatch accordingly:

__. assertThat(__.hasSize(5), __.failsToMatch('long string', __.containsString('size was <11>')));

Combining matchers

allOf(matchers...)

Matches if all given matchers match:

__.assertThat('an expected value', __.allOf(__.containsString('expected'), __.containsString('value')); // Passes

__.assertThat('another value', __.allOf(__.containsString('expected'), __.containsString('value')); // Fails

anyOf(matchers...)

Matches if at least one of the given matchers matches:

__.assertThat('great value offer', __.anyOf(__.containsString('special'), __.containsString('great value')); // Passes
__.assertThat('special offer', __.anyOf(__.containsString('special'), __.containsString('great value')); // Passes

__.assertThat('great offer', __.anyOf(__.containsString('special'), __.containsString('great value')); // Fails

Promise matchers

All promise matchers are also promising matchers by nature and therefore must be used with promiseThat(...). See Hamjest and Promises for details.

fulfilled([matcherOrValue]) / isFulfilledWith([matcherOrValue]) / willBe([matcherOrValue])

Matches promises that will eventually be fulfilled. If a matcher or value is provided, it is used to verify the the fulfillment value:

return __.promiseThat(Q(), __.is(__.fulfilled())); // Passes
return __.promiseThat(Q('fulfillment value'), __.is(__. fulfilled())); // Passes
return __.promiseThat(Q('fulfillment value'), __.is(__.fulfilled(__.containsString('value'))); // Passes
return __.promiseThat(Q('fulfillment value'), __.is(__.fulfilledWith(__.containsString('value'))); // Same as above
return __.promiseThat(Q('fulfillment value'), __.willBe(__.containsString('value'))); // Same as above

var deferred = Q.defer();
setTimeout(deferred.resolve, 1000);
return __.promiseThat(deferred.promise, __.is(__.fulfilled()); // Passes when the promise is fulfilled, even though it is still pending

__.promiseThat(Q.reject(), __.is(__.fulfilled())); // Fails because the promise will be rejected
__.promiseThat(Q('some value'), __.willBe('expected value'))); // Fails because the fulfillment value does not match

rejected([matcherOrValue]) / isRejectedWith([matcherOrValue])

Matches promises that will eventually be rejected. If a matcher or value is provided, it is used to verify the the rejection value:

return __.promiseThat(Q.reject(), __.is(__.rejected())); // Passes
return __.promiseThat(Q.reject('odd reason'), __.is(__.rejected())); // Passes
return __.promiseThat(Q.reject('odd reason'), __.is(__.rejected(__.containsString('odd'))); // Passes

var deferred = Q.defer();
setTimeout(deferred.reject, 1000);
return __.promiseThat(deferred.promise, __.is(__.rejected()); // Passes when the promise is rejected, even though it is still pending

__.promiseThat(Q('a value'), __.is(__.rejected())); // Fails because the promise will be fulfilled
__.promiseThat(Q.reject('some reason'), __.is(__.rejected(__.containsString('odd'))); // Fails because the rejection value does not match