Should.js is included in Unit.JS, you can use Should.js with Unit.js :
var test = require('unit.js');
// test 'string' type
test.should('foobar').be.type('string');
// then that actual value '==' expected value
test.should('foobar' == 'foobar').be.ok;
// then that actual value '===' expected value
test.should('foobar').be.equal('foobar');
// Should.js library (alternative style)
var should = test.should;
// test 'string' type
('foobar').should.be.type('string');
// then that actual value '==' expected value
('foobar' == 'foobar').should.be.ok;
// then that actual value '===' expected value
('foobar').should.be.equal('foobar');
// this shortcut works also like this
// test 'string' type
should('foobar').be.type('string');
// then that actual value '==' expected value
should('foobar' == 'foobar').be.ok;
// then that actual value '===' expected value
should('foobar').be.equal('foobar');
Should.js adds a non enumerable property in Object.prototype.should
to be able to make assertions like
myVar.should.be.String;
.
This does not affect the signature of objects because the property is invisible (not enumerable).
If necessary you can cancel it:
delete Object.prototype.should;
Subsequently Should.js can be used in this way:
test.should(myVar).be.String;
Must.js done the same, so to remove the 2 monkey patches:
var test = require('unit.js');
delete Object.prototype.must;
delete Object.prototype.should;
This documentation below is written by the contributors of Should.js and restructured by me (Nicolas Talle).
should is an expressive, readable, test framework agnostic, assertion library. Main goals of this library to be expressive and to be helpful. It means test code should be clean, and error messages enough helpfull to understand error.
It extends the Object.prototype
with a single non-enumerable getter that allows you to express how that object should behave, also it returns itself when required with require
.
Example
var should = require('should');
var user = {
name: 'tj'
, pets: ['tobi', 'loki', 'jane', 'bandit']
};
user.should.have.property('name', 'tj');
user.should.have.property('pets').with.lengthOf(4);
// if the object was created with Object.create(null)
// then it doesn't inherit `Object` and have the `should` getter
// so you can do:
should(user).have.property('name', 'tj');
should(true).ok;
someAsyncTask(foo, function(err, result){
should.not.exist(err);
should.exist(result);
result.bar.should.equal(foo);
});
should
Our function should
Parameters:
obj
any Object to assert
Examples:
var should = require('should');
should('abc').be.a.String();
Returns should.Assertion Returns new Assertion for beginning assertion chain
config
Object with configuration. It contains such properties:
checkProtoEql
boolean - Affect if.eql
will check objects prototypesplusZeroAndMinusZeroEqual
boolean - Affect if.eql
will treat +0 and -0 as equal Also it can contain options for should-format.
Type: Object
Examples:
var a = { a: 10 }, b = Object.create(null);
b.a = 10;
a.should.be.eql(b);
//not throws
should.config.checkProtoEql = true;
a.should.be.eql(b);
//throws AssertionError: expected { a: 10 } to equal { a: 10 } (because A and B have different prototypes)
extend
Allow to extend given prototype with should property using given name. This getter will unwrap all standard wrappers like Number
, Boolean
, String
.
Using should(obj)
is the equivalent of using obj.should
with known issues (like nulls and method calls etc).
To add new assertions, need to use Assertion.add method.
Parameters:
propertyName
string? Name of property to add. Default is'should'
.proto
Object? Prototype to extend with. Default isObject.prototype
.
Examples:
var prev = should.extend('must', Object.prototype);
'abc'.must.startWith('a');
var should = should.noConflict(prev);
should.not.exist(Object.prototype.must);
Returns {name: string, descriptor: Object, proto: Object} Descriptor enough to return all back
noConflict
Delete previous extension. If desc
missing it will remove default extension.
Parameters:
Examples:
var should = require('should').noConflict();
should(Object.prototype).not.have.property('should');
var prev = should.extend('must', Object.prototype);
'abc'.must.startWith('a');
should.noConflict(prev);
should(Object.prototype).not.have.property('must');
Returns Function Returns should function
use
Simple utility function for a bit more easier should assertion extension
Parameters:
f
Function So called plugin function. It should accept 2 arguments:should
function andAssertion
constructor
Examples:
should.use(function(should, Assertion) {
Assertion.add('asset', function() {
this.params = { operator: 'to be asset' };
this.obj.should.have.property('id').which.is.a.Number();
this.obj.should.have.property('path');
})
})
Returns Function Returns should
function
Static should and assert module
For some rare cases should can be used statically, without Object.prototype
.
It can be replacement for node assert module:
assert.fail(actual, expected, message, operator) // just write wrong should assertion
assert(value, message), assert.ok(value, [message]) // should(value).ok
assert.equal(actual, expected, [message]) // should(actual).eql(expected, [message])
assert.notEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])
assert.deepEqual(actual, expected, [message]) // should(actual).eql(expected, [message])
assert.notDeepEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])
assert.strictEqual(actual, expected, [message]) // should(actual).equal(expected, [message])
assert.notStrictEqual(actual, expected, [message]) // should(actual).not.equal(expected, [message])
assert.throws(block, [error], [message]) // should(block).throw([error])
assert.doesNotThrow(block, [message]) // should(block).not.throw([error])
assert.ifError(value) // should(value).Error (to check if it is error) or should(value).not.ok (to check that it is falsy)
Optional Error description
As it can often be difficult to ascertain exactly where failed assertions are coming from in your tests, an optional description parameter can be passed to several should matchers. The description will follow the failed assertion in the error:
(1).should.eql(0, 'some useful description')
AssertionError: some useful description
at Object.eql (/Users/swift/code/should.js/node_modules/should/lib/should.js:280:10)
...
Examples of methods that support this optional description: eql
, equal
, within
, instanceof
, above
, below
, match
, length
, property
, ownProperty
.
Assertions
chaining assertions
Every assertion will return a should.js
-wrapped Object, so assertions can be chained.
You can use this helpers to just chain: .an
, .of
, .a
, .and
, .be
, .have
, .with
, .is
, .which
. Use them for better readability, they do nothing at all.
For example:
user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');
user.pets.should.be.instanceof(Array).and.have.lengthOf(4);
Almost all assertions return the same object - so you can easy chain them. But some move assertion object to property value. See feather, it will be mention if object chainged.
AssertionError
should AssertionError
Parameters:
options
Object
Assertion
should Assertion
Parameters:
obj
any Given object for assertion
assert
Base method for assertions.
Before calling this method need to fill Assertion#params object. This method usually called from other assertion methods.
Assertion#params
can contain such properties:
operator
- required string containing description of this assertionobj
- optional replacement for this.obj, it is useful if you prepare more clear object then givenmessage
- if this property filled with string any others will be ignored and this one used as assertion messageexpected
- any object used when you need to assert relation between given object and expected. Like given == expected (== is a relation)details
- additional string with details to generated message
Parameters:
expr
any Any expression that will be used as a condition for asserting.
Examples:
var a = new should.Assertion(42);
a.params = {
operator: 'to be magic number',
}
a.assert(false);
//throws AssertionError: expected 42 to be magic number
fail
Shortcut for Assertion#assert(false)
.
Examples:
var a = new should.Assertion(42);
a.params = {
operator: 'to be magic number',
}
a.fail();
//throws AssertionError: expected 42 to be magic number
add
Way to extend Assertion function. It uses some logic to define only positive assertions and itself rule with negative assertion.
All actions happen in subcontext and this method take care about negation. Potentially we can add some more modifiers that does not depends from state of assertion.
Parameters:
name
String Name of assertion. It will be used for defining method or getter on Assertion.prototypefunc
Function Function that will be called on executing assertion
Examples:
Assertion.add('asset', function() {
this.params = { operator: 'to be asset' }
this.obj.should.have.property('id').which.is.a.Number()
this.obj.should.have.property('path')
})
addChain
Add chaining getter to Assertion like .a, .which etc
Parameters:
alias
Create alias for some Assertion
property
Parameters:
Examples:
Assertion.alias('true', 'True')
PromisedAssertion
Assertion used to delegate calls of Assertion methods inside of Promise. It has almost all methods of Assertion.prototype
Parameters:
obj
Promise
not
Negation modifier. Current assertion chain become negated. Each call invert negation on current assertion.
any
Any modifier - it affect on execution of sequenced assertion to do not check all
, but check any of
.
only
Only modifier - currently used with .keys to check if object contains only exactly this .keys
fail
Node.js standard assert.fail
.
Parameters:
actual
any Actual objectexpected
any Expected objectmessage
string Message for assertionoperator
string Operator textstackStartFunction
ok
Node.js standard assert.ok
.
Parameters:
value
anymessage
string?
Assert given object is truthy according javascript type conversions ('', null, undefined, 0 , NaN, Infinity - is falsy, so all others are truthy).
Examples:
Assert truthfulness:
(true).should.be.ok();
'yay'.should.be.ok();
(10).should.be.ok();
({}).should.be.ok();
should(10).be.ok();
should({}).be.ok();
or negated:
false.should.not.be.ok();
''.should.not.be.ok();
(0).should.not.be.ok();
should(0).not.be.ok();
should('').not.be.ok();
equal
Exact comparison using ===
.
Assert if asserted object strictly equal to expected
(using ===
- no type conversion for primitive types and reference equivalence for reference types).
Node.js standard assert.equal
.
Parameters:
actual
anyexpected
any Expected valuemessage
string? Optional message
Examples:
10.should.be.equal(10);
'a'.should.be.exactly('a');
should(null).be.exactly(null);
notEqual
Node.js standard assert.notEqual
.
Parameters:
actual
anyexpected
anymessage
string?
deepEqual
Node.js standard assert.deepEqual
.
But uses should.js .eql implementation instead of Node.js own deepEqual.
Parameters:
actual
anyexpected
anymessage
string?
notDeepEqual
Node.js standard assert.notDeepEqual
.
But uses should.js .eql implementation instead of Node.js own deepEqual.
Parameters:
actual
anyexpected
anymessage
string?
strictEqual
Node.js standard assert.strictEqual
.
Parameters:
actual
anyexpected
anymessage
string?
notStrictEqual
Node.js standard assert.notStrictEqual
.
Parameters:
actual
anyexpected
anymessage
string?
throws
Node.js standard assert.throws
.
Parameters:
doesNotThrow
Node.js standard assert.doesNotThrow
.
Parameters:
ifError
Node.js standard assert.ifError
.
Parameters:
err
Error
should.exists
Assert obj exists, with optional message.
Parameters:
obj
anymsg
String?
Examples:
should.exist(1);
should.exist(new Date());
not.exist
Asserts obj does not exist, with optional message.
Parameters:
obj
anymsg
String?
Examples:
should.not.exist(null);
should.not.exist(void 0);
be
Simple chaining to improve readability. Does nothing.
Properties
be
should.Assertion
true
Assert given object is exactly true
.
Parameters:
message
string? Optional message
Examples:
(true).should.be.true();
false.should.not.be.true();
({ a: 10}).should.not.be.true();
false
Assert given object is exactly false
.
Parameters:
message
string? Optional message
Examples:
(true).should.not.be.false();
false.should.be.false();
NaN
Assert given object is NaN (not a number)
Examples:
(10).should.not.be.NaN();
NaN.should.be.NaN();
(undefined + 0).should.be.NaN;
Infinity
Assert numeric value is Infinity (not finite, positive or negative)
Examples:
(1/0).should.be.Infinity;
(10).should.not.be.Infinity();
NaN.should.not.be.Infinity();
within
Assert given number between start
and finish
or equal one of them.
Assert inclusive numeric range (<= start
and >= finish
):
Parameters:
Examples:
user.age.should.be.within(5, 50);
(10).should.be.within(0, 20);
(5).should.be.within(5, 10).and.within(5, 5);
approximately
Assert given (floating point) number near some other value
within delta
margin
Parameters:
Examples:
(9.99).should.be.approximately(10, 0.1);
(99.99).should.be.approximately(100, 0.1);
above
Assert given number above the given value (> n
).
Parameters:
Examples:
(10).should.be.below(0);
(5).should.be.above(0);
(5).should.not.be.above(5);
user.age.should.be.above(5);
user.age.should.not.be.above(100);
below
Assert given number below the given value (< n
).
Parameters:
Examples:
(0).should.be.below(10);
(5).should.be.below(6);
(5).should.not.be.below(5);
user.age.should.be.below(100);
user.age.should.not.be.below(5);
aboveOrEqual
Assert given number above n
.
Parameters:
Examples:
(10).should.be.aboveOrEqual(0);
(10).should.be.aboveOrEqual(10);
belowOrEqual
Assert given number below n
.
Parameters:
Examples:
(0).should.be.belowOrEqual(10);
(0).should.be.belowOrEqual(0);
Number
Assert given object is number
arguments
Assert given object is arguments
Examples:
var args = (function(){ return arguments; })(1,2,3);
args.should.be.arguments();
[].should.not.be.arguments();
type
Assert given object has some type using typeof
operator
Parameters:
Examples:
user.should.be.type('object');
'test'.should.be.type('string');
instanceof
Assert given object is instance of constructor
Parameters:
Examples:
user.should.be.an.instanceof(User);
[].should.be.an.instanceOf(Array);
Type assertion
Assert given object is instance of such constructor (shortcut for .instanceof
assertion).
({}).should.be.an.Object();
(1).should.be.a.Number();
[].should.be.an.Array.and.an.Object();
(true).should.be.a.Boolean();
''.should.be.a.String();
Function
Assert given object is function
Object
Assert given object is object
String
Assert given object is string
Array
Assert given object is array
Boolean
Assert given object is boolean
Error
Assert given object is error
Date
Assert given object is a date
null
Assert given object is null
class
Assert given object has some internal [[Class]], via Object.prototype.toString call
undefined
Assert given object is undefined
iterable
Assert given object supports es6 iterable protocol (just check that object has property Symbol.iterator, which is a function)
iterator
Assert given object supports es6 iterator protocol (just check that object has property next, which is a function)
generator
Assert given object is a generator object
eql
Deep object equality comparison. Assert if asserted object is equal to otherValue. This means that object compared by its actual content, not just reference equality.
For full spec see should-equal tests
.
Parameters:
val
any Expected valuedescription
string? Optional message
Examples:
(10).should.be.eql(10);
('10').should.not.be.eql(10);
(-0).should.not.be.eql(+0);
NaN.should.be.eql(NaN);
({ a: 10}).should.be.eql({ a: 10 });
[ 'a' ].should.not.be.eql({ '0': 'a' });
equalOneOf
Exact comparison using === to be one of supplied objects.
Parameters:
vals
(Array | any) Expected values
Examples:
'ab'.should.be.equalOneOf('a', 10, 'ab');
'ab'.should.be.equalOneOf(['a', 10, 'ab']);
oneOf
Exact comparison using .eql to be one of supplied objects.
Parameters:
vals
(Array | any) Expected values
Examples:
({a: 10}).should.be.oneOf('a', 10, 'ab', {a: 10});
({a: 10}).should.be.oneOf(['a', 10, 'ab', {a: 10}]);
Promise
Assert given object is a Promise
Examples:
promise.should.be.Promise()
(new Promise(function(resolve, reject) { resolve(10); })).should.be.a.Promise()
(10).should.not.be.a.Promise()
fulfilled
Assert given promise will be fulfilled. Result of assertion is still .thenable and should be handled accordingly.
Examples:
// don't forget to handle async nature
(new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled();
// test example with mocha it is possible to return promise
it('is async', () => {
return new Promise(resolve => resolve(10))
.should.be.fulfilled();
});
Returns Promise
rejected
Assert given promise will be rejected. Result of assertion is still .thenable and should be handled accordingly.
Examples:
// don't forget to handle async nature
(new Promise(function(resolve, reject) { resolve(10); }))
.should.not.be.rejected();
// test example with mocha it is possible to return promise
it('is async', () => {
return new Promise((resolve, reject) => reject(new Error('boom')))
.should.be.rejected();
});
Returns Promise
fulfilledWith
Assert given promise will be fulfilled with some expected value (value compared using .eql). Result of assertion is still .thenable and should be handled accordingly.
Examples:
// don't forget to handle async nature
(new Promise(function(resolve, reject) { resolve(10); }))
.should.be.fulfilledWith(10);
// test example with mocha it is possible to return promise
it('is async', () => {
return new Promise((resolve, reject) => resolve(10))
.should.be.fulfilledWith(10);
});
Returns Promise
rejectedWith
Assert given promise will be rejected with some sort of error. Arguments is the same for Assertion#throw. Result of assertion is still .thenable and should be handled accordingly.
Examples:
function failedPromise() {
return new Promise(function(resolve, reject) {
reject(new Error('boom'))
})
}
failedPromise().should.be.rejectedWith(Error);
failedPromise().should.be.rejectedWith('boom');
failedPromise().should.be.rejectedWith(/boom/);
failedPromise().should.be.rejectedWith(Error, { message: 'boom' });
failedPromise().should.be.rejectedWith({ message: 'boom' });
// test example with mocha it is possible to return promise
it('is async', () => {
return failedPromise().should.be.rejectedWith({ message: 'boom' });
});
Returns Promise
finally
Assert given object is promise and wrap it in PromisedAssertion, which has all properties of Assertion. That means you can chain as with usual Assertion. Result of assertion is still .thenable and should be handled accordingly.
Examples:
(new Promise(function(resolve, reject) { resolve(10); }))
.should.be.eventually.equal(10);
// test example with mocha it is possible to return promise
it('is async', () => {
return new Promise(resolve => resolve(10))
.should.be.finally.equal(10);
});
Returns PromisedAssertion Like Assertion, but .then this.obj in Assertion
startWith
Assert given string starts with prefix (str
).
Parameters:
Examples:
'abc'.should.startWith('a');
endWith
Assert given string ends with prefix (str
).
Parameters:
Examples:
'abca'.should.endWith('a');
containEql
Assert that given object contain something that equal to other
. It uses should-equal
for equality checks.
If given object is array it search that one of elements was equal to other
.
If given object is string it checks if other
is a substring - expected that other
is a string.
If given object is Object it checks that other
is a subobject - expected that other
is a object.
Parameters:
other
any Nested object
Examples:
[1, 2, 3].should.containEql(1);
[1, 2, 3].should.containEql(3);
[[1],[2],[3]].should.containEql([3]);
[[1],[2],[3, 4]].should.not.containEql([3]);
'hello boy'.should.containEql('boy');
'abc'.should.containEql('b');
'ab1c'.should.containEql(1);
[{ a: 1 }, 'a', 10].should.containEql({ a: 1 });
({ a: 10, c: { d: 10 }}).should.containEql({ a: 10 });
({ a: 10, c: { d: 10 }}).should.containEql({ c: { d: 10 }});
({ a: 10, c: { d: 10 }}).should.containEql({ b: 10 });
// throws AssertionError: expected { a: 10, c: { d: 10 } } to contain { b: 10 }
// expected { a: 10, c: { d: 10 } } to have property b
containDeepOrdered
Assert that given object is contain equally structured object on the same depth level.
If given object is an array and other
is an array it checks that the eql elements is going in the same sequence in given array (recursive)
If given object is an object it checks that the same keys contain deep equal values (recursive)
On other cases it try to check with .eql
Parameters:
other
any Nested object
Examples:
[ 1, 2, 3].should.containDeepOrdered([1, 2]);
[ 1, 2, [ 1, 2, 3 ]].should.containDeepOrdered([ 1, [ 2, 3 ]]);
({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({a: 10});
({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {c: 10}});
({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {d: [1, 3]}});
containDeep
The same like Assertion#containDeepOrdered
but all checks on arrays without order.
It does not search somewhere in depth it check all pattern in depth. Object checked
by properties key and value, arrays checked like sub sequences. Everyting compared using .eql
.
Main difference with .containEql
is that this assertion require full type chain -
if asserted value is an object, other
value should be also an object (which is sub object of given).
The same true for arrays, other
value should be an array which compared to be subsequence of given object.
Parameters:
other
any Nested object
Examples:
[ 1, 2, 3].should.containDeep([2, 1]);
[ 1, 2, [ 1, 2, 3 ]].should.containDeep([ 1, [ 3, 1 ]]);
'hello boy'.should.containDeep('boy');
[1,2,3].should.containDeep([3]);
[1,2,3].should.containDeep([1, 3]);
//but not
[1,2,3].should.containDeep([3, 1]);
propertyWithDescriptor
Asserts given object has some descriptor. On success it change given object to be value of property.
Parameters:
name
string Name of propertydesc
Object Descriptor like used in Object.defineProperty (not required to add all properties)
Examples:
({ a: 10 }).should.have.propertyWithDescriptor('a', { enumerable: true });
property
Asserts given object has property with optionally value. On success it change given object to be value of property.
Parameters:
name
string Name of propertyval
any? Optional property value to check
Examples:
({ a: 10 }).should.have.property('a');
[1, 2].should.have.property('0', 1);
user.should.have.property('name');
user.should.have.property('age', 15);
user.should.not.have.property('rawr');
user.should.not.have.property('age', 0);
properties
Asserts given object has properties. On this method affect .any
modifier, which allow to check not all properties.
Examples:
({ a: 10 }).should.have.properties('a');
({ a: 10, b: 20 }).should.have.properties([ 'a' ]);
({ a: 10, b: 20 }).should.have.properties([ 'a', 'b' ]);
({ a: 10, b: 20 }).should.have.properties({ b: 20 });
length
Asserts given object has property length
with given value n
Parameters:
Examples:
[1, 2].should.have.length(2);
ownProperty
Asserts given object has own property. On success it change given object to be value of property.
Parameters:
Examples:
({ a: 10 }).should.have.ownProperty('a');
({ foo: 'bar' }).should.have.ownProperty('foo').equal('bar');
empty
Asserts given object is empty. For strings, arrays and arguments it checks .length
property, for objects it checks keys.
Examples:
''.should.be.empty();
[].should.be.empty();
({}).should.be.empty();
(function() {
arguments.should.be.empty();
})();
keys
Asserts given object has such keys. Compared to properties
, keys
does not accept Object
as a argument.
When calling via .key
current object in assertion changed to value of this key
Parameters:
keys
...any Keys to check
Examples:
var obj = { foo: 'bar', baz: 'raz' };
obj.should.have.keys('foo', 'baz');
({ a: 10 }).should.have.keys('a');
({ a: 10, b: 20 }).should.have.keys('a', 'b');
(new Map([[1, 2]])).should.have.key(1);
json.should.have.only.keys('type', 'version')
//fail AssertionError: expected {} to have key 'key'missing keys: 'key'
({}).should.have.keys('key');
value
Asserts given object has such value for given key
Parameters:
key
any Key to checkvalue
any Value to check
Examples:
({ a: 10 }).should.have.value('a', 10);
(new Map([[1, 2]])).should.have.value(1, 2);
size
Asserts given object has such size.
Parameters:
s
number Size to check
Examples:
({ a: 10 }).should.have.size(1);
(new Map([[1, 2]])).should.have.size(1);
propertyByPath
Asserts given object has nested property in depth by path. On success it change given object to be value of final property.
Examples:
({ a: {b: 10}}).should.have.propertyByPath('a', 'b').eql(10);
throw
Assert given function throws error with such message.
Parameters:
message
(string | RegExp | Function | Object | GeneratorFunction | GeneratorObject)? Message to match or propertiesproperties
Object? Optional properties that will be matched to thrown error
Examples:
(function(){ throw new Error('fail') }).should.throw();
(function(){ throw new Error('fail') }).should.throw('fail');
(function(){ throw new Error('fail') }).should.throw(/fail/);
(function(){ throw new Error('fail') }).should.throw(Error);
var error = new Error();
error.a = 10;
(function(){ throw error; }).should.throw(Error, { a: 10 });
(function(){ throw error; }).should.throw({ a: 10 });
(function*() {
yield throwError();
}).should.throw();
If you need to check something in asynchronous function it is required to do in 2 steps:
// first we need to check that function is called
var called = false;
collection.findOne({ _id: 10 }, function(err, res) {
called = true;
//second we test what you want
res.should.be....
});
called.should.be.true;
In case you are using something like Mocha
, you should use asynchronous test and call done()
in proper place to make sure that you asynchronous function is called before test is finished.
collection.findOne({ _id: 10 }, function(err, res) {
if(err) return done(err);
//second we test what you want
res.should.be....
done();
});
In general case if you need to check that something is executed you need such thing as spies
, good example is an sinon.
match
Asserts if given object match other
object, using some assumptions:
First object matched if they are equal,
If other
is a regexp and given object is a string check on matching with regexp
If other
is a regexp and given object is an array check if all elements matched regexp
If other
is a regexp and given object is an object check values on matching regexp
If other
is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
If other
is an object check if the same keys matched with above rules
All other cases failed.
Usually it is right idea to add pre type assertions, like .String()
or .Object()
to be sure assertions will do what you are expecting.
Object iteration happen by keys (properties with enumerable: true), thus some objects can cause small pain. Typical example is js
Error - it by default has 2 properties name
and message
, but they both non-enumerable. In this case make sure you specify checking props (see examples).
Parameters:
other
any Object to matchdescription
string? Optional message
Examples:
'foobar'.should.match(/^foo/);
'foobar'.should.not.match(/^bar/);
({ a: 'foo', c: 'barfoo' }).should.match(/foo$/);
['a', 'b', 'c'].should.match(/[a-z]/);
(5).should.not.match(function(n) {
return n < 0;
});
(5).should.not.match(function(it) {
it.should.be.an.Array();
});
({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should
.match({ a: 10, b: /c$/, c: function(it) {
return it.should.have.property('d', 10);
}});
[10, 'abc', { d: 10 }, 0].should
.match({ '0': 10, '1': /c$/, '2': function(it) {
return it.should.have.property('d', 10);
}});
var myString = 'abc';
myString.should.be.a.String().and.match(/abc/);
myString = {};
myString.should.match(/abc/); //yes this will pass
//better to do
myString.should.be.an.Object().and.not.empty().and.match(/abc/);//fixed
(new Error('boom')).should.match(/abc/);//passed because no keys
(new Error('boom')).should.not.match({ message: /abc/ });//check specified property
matchEach
Asserts if given object values or array elements all match other
object, using some assumptions:
First object matched if they are equal,
If other
is a regexp - matching with regexp
If other
is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
All other cases check if this other
equal to each element
Parameters:
other
any Object to matchdescription
string? Optional message
Examples:
[ 'a', 'b', 'c'].should.matchEach(/\w+/);
[ 'a', 'a', 'a'].should.matchEach('a');
[ 'a', 'a', 'a'].should.matchEach(function(value) { value.should.be.eql('a') });
{ a: 'a', b: 'a', c: 'a' }.should.matchEach(function(value) { value.should.be.eql('a') });
matchAny
Asserts if any of given object values or array elements match other
object, using some assumptions:
First object matched if they are equal,
If other
is a regexp - matching with regexp
If other
is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
All other cases check if this other
equal to each element
Parameters:
other
any Object to matchdescription
string? Optional message
Examples:
[ 'a', 'b', 'c'].should.matchAny(/\w+/);
[ 'a', 'b', 'c'].should.matchAny('a');
[ 'a', 'b', 'c'].should.matchAny(function(value) { value.should.be.eql('a') });
{ a: 'a', b: 'b', c: 'c' }.should.matchAny(function(value) { value.should.be.eql('a') });
freeSelf
Detect free variable self
.
root
Used as a reference to the global object.