Skip to content


Subversion checkout URL

You can clone with
Download ZIP
674 lines (486 sloc) 19.253 kb

Repo was moved to own organization. See


should is an expressive, readable, test framework agnostic, assertion library. Main goals of this library to be expressive and to be helpful. It keeps your test code clean, and your error messages helpful.

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.


var should = require('should');

var user = {
    name: 'tj'
  , pets: ['tobi', 'loki', 'jane', 'bandit']
};'name', 'tj');'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)'name', 'tj');

someAsyncTask(foo, function(err, result){

To begin

  1. Install it:

    $ npm install should --save-dev
  2. Require it and use:

    var should = require('should');

In browser

Well, even when browsers by complains of authors has 100% es5 support, it does not mean it has not bugs. Please see wiki for known bugs.

If you want to use should in browser, use the should.js file in the root of this repository, or build it yourself. It is built with browserify (see Makefile). To build a fresh version:

# you should have browserify
$ npm install -g browserify
$ make browser

The script is exported to window.Should. It is the same as using should statically:


Also, in the case of node.js, Object.prototype is extended with should (hence the capital S in window.Should):;
// the same
// window is host object;
// you should not really care about it


should.js uses EcmaScript 5 very extensively so any browser that support ES5 is supported. (IE <=8 not supported). See kangax's compat table to know which exactly.

You can easy install it with npm or bower:

npm install should --save-dev
# or
bower install visionmedia/should.js

Static should and assert module

For some rare cases should can be used statically, without Object.prototype. It can be a replacement for the node assert module:, 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)


.not negate current assertion.


.any allow for assertions with multiple parameters to assert on any of parameters (not all)


chaining assertions

Every assertion will return a should.js-wrapped Object, so assertions can be chained. To help chained assertions read more clearly, you can use the following helpers anywhere in your chain: .an, .of, .a, .and, .be, .have, .with, .is, .which. Use them for better readability; they do nothing at all. For example:'name', 'tj');;

Almost all assertions return the same object - so you can easy chain them. But some (eg: .length and .property) move the assertion object to a property value, so be careful.


Assert if chained object is truthy in javascript (ie: not '', null, undefined, 0 , NaN).

Assert truthfulness:;

or negated:;

Warning: No assertions can be done on null and undefined. e.g.;

will give you Uncaught TypeError: Cannot read property 'should' of undefined).

In order to test for null use

(err === null);


Assert if chained object === true:;


Assert if chained object === false:;


Assert if chained object is equal to otherValue. The object is compared by its actual content, not just reference equality.

({ foo: 'bar' }).should.eql({ foo: 'bar' });
// see next example it is correct, even if it is different types, but actual content the same
[1, 2, 3].should.eql({ '0': 1, '1': 2, '2': 3 });

.equal(otherValue) and .exactly(otherValue)

Assert if chained object is strictly equal to otherValue (using === - no type conversion for primitive types and reference equivalence for reference types).



Assert that a string starts with str.



Assert that a string ends with str.


.within(from, to)

Assert inclusive numeric range (<= to and >= from):, 50);
(5), 10).and.within(5, 5);

.approximately(num, delta)

Assert floating point number near num within delta margin:

(99.99), 0.1);

.above(num) and .greaterThan(num)

Assert numeric value above the given value (> num):;;

.below(num) and .lessThan(num)

Assert numeric value below the given value (< num):;;


Assert numeric value is NaN:

(undefined + 0);


Assert numeric value is Infinity:



Assert given object is of a particular type (using typeof operator):'object');

.instanceof(constructor) and .instanceOf(constructor)

Assert given object is an instance of constructor (using instanceof operator):;


Assert given object is an Arguments:

var args = (function(){ return arguments; })(1,2,3);;

.Object, .Number, .Array, .Boolean, .Function, .String, .Error

Assert given object is instance of the given constructor (shortcut for .instanceof assertion).


.enumerable(name[, value])

Assert a property exists, is enumerable, and has optional value (compare using .eql):

user.should.have.enumerable('age', 15);
user.should.not.have.enumerable('age', 0);
[1, 2].should.have.enumerable('0', 1);

.property(name[, value])

Assert property exists and has optional value (compare using .eql):'name');'age', 15);'rawr');'age', 0);
[1, 2]'0', 1);

NB .property changes the chain's object to the given property's value, so be careful when chaining after .property!

.properties(propName1, propName2, ...) or .properties([propName1, propName2, ...]) or .properties(obj)

obj should be an object that maps properties to their actual values.

Assert all given properties exist and have given values (compare using .eql):'name', 'age');['name', 'age']);{
    name: 'denis',
    age: 24

.length(number) and .lengthOf(number)

Assert length property exists and has a value of the given number (shortcut for .property('length', number)):

({ length: 10}).should.have.length(10);

NB .length and .lengthOf change the chain's object to the given length value, so be careful when chaining!

.ownProperty(str) and .hasOwnProperty(str)

Assert given object has own property (using .hasOwnProperty):

({ foo: 'bar' }).should.have.ownProperty('foo').equal('bar');

NB .ownProperty and .hasOwnProperty change the chain's object to the given property value, so be careful when chaining!


Assert given value is empty. Strings, arrays, arguments with a length of 0, and objects without their own properties, are considered empty.

(function() {;

.keys([key1, key2, ...]) and .keys(key1, key2, ...) and .key(key)

Assert own object keys, which must match exactly, and will fail if you omit a key or two:

var obj = { foo: 'bar', baz: 'raz' };
obj.should.have.keys('foo', 'baz');
obj.should.have.keys(['foo', 'baz']);
({}).should.have.keys('key'); //fail AssertionError: expected {} to have key 'key'missing keys: 'key'


Assert given value to contain something .eql to otherValue. See examples to understand better:

'hello boy'.should.containEql('boy');
[[1],[2],[3, 4]].should.not.containEql([3]);

({ b: 10 }).should.containEql({ b: 10 });
([1, 2, { a: 10 }]).should.containEql({ a: 10 });
[1, 2, 3].should.not.containEql({ a: 1 });

[{a: 'a'}, {b: 'b', c: 'c'}].should.containEql({a: 'a'});
[{a: 'a'}, {b: 'b', c: 'c'}].should.not.containEql({b: 'b'});

When .containEql check arrays it check elements to be in the same order in otherValue and object just to be presented.


Assert given value to contain something .eql to otherValue within depth. Again see examples:

'hello boy'.should.containDeep('boy');
[1,2,3].should.containDeep([1, 3]);
//but not
[1,2,3].should.containDeep([3, 1]);

({ a: { b: 10 }, b: { c: 10, d: 11, a: { b: 10, c: 11} }}).should
  .containDeep({ a: { b: 10 }, b: { c: 10, a: { c: 11 }}});

[1, 2, 3, { a: { b: { d: 12 }}}].should.containDeep([{ a: { b: {d: 12}}}]);

[[1],[2],[3, 4]].should.containDeep([[3]]);
[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{a: 'a'}]);
[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{b: 'b'}]);

It does not search somewhere in depth it check all pattern in depth. Objects are checked by properties key and value; arrays are checked like sub sequences. Everyting is compared using .eql. Main difference with .containEql is that this assertion requires full type chain - if asserted value is an object, otherValue should be also an object (which is sub object of given). The same is true for arrays, otherValue should be an array which compared to be subsequence of given object.

When .containDeep check arrays it check elements to be in the same order (as arrays ordered collections) in otherValue and object just to be presented.


Assert given object matches otherValue.

Given: String, otherValue: regexp. Uses RegExp#exec(str):


Given: Array, otherValue: regexp - assert each value match to regexp.

['a', 'b', 'c'].should.match(/[a-z]/);
['a', 'b', 'c'].should.not.match(/[d-z]/);

Given: Object, otherValue: regexp - assert own property's values to match regexp.

({ a: 'foo', c: 'barfoo' }).should.match(/foo$/);
({ a: 'a' }).should.not.match(/^http/);

Given: Anything, otherValue: function - assert if given value matched to function.

Function can use .should inside or return 'true' or 'false', in all other cases it do nothing. If you return value that return assertion, you will receive better error messages.

(5).should.match(function(n) { return n > 0; });
(5).should.not.match(function(n) { return n < 0; });
(5).should.not.match(function(it) {; });
(5).should.match(function(it) { return; });

Now compare messages:

(5).should.not.match(function(it) {; });
//AssertionError: expected 5 not to match [Function]
(5).should.not.match(function(it) { return; });
//AssertionError: expected 5 not to match [Function]
//  expected 5 to be a number

Given: object, otherValue: another object - assert that object properties match to properties of another object in meaning that describe above cases. See examples:

({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should
    .match({ a: 10, b: /c$/, c: function(it) { return'd', 10); }});

[10, 'abc', { d: 10 }, 0].should
    .match({ '0': 10, '1': /c$/, '2': function(it) { return'd', 10); } });

[10, 'abc', { d: 10 }, 0].should
    .match([10, /c$/, function(it) { return'd', 10); }]);


Assert given property keys and values each match given check object.

If otherValue is RegExp, then each property value checked to match it:

(['a', 'b', 'c']).should.matchEach(/[a-c]/);

If otherValue is Function, then check each property value and key matched it:

[10, 11, 12].should.matchEach(function(it) { return it >= 10; });
[10, 11, 12].should.matchEach(function(it) { return it >= 10; });

In other cases it checks that each property value is .eql to otherValue:

[10, 10].should.matchEach(10);

.throw() and throwError()

Assert an exception is thrown:

  throw new Error('fail');

Assert an exception is not thrown:



Assert exception message matches string:

  throw new Error('fail');

Assert exepection message matches regexp:

  throw new Error('failed to foo');

If you need to pass arguments and/or context to execute function use Function#bind(context, arg1, ...):

function isPositive(n) {
    if(n <= 0) throw new Error('Given number is not positive')

isPositive.bind(null, 10).should.not.throw();
isPositive.bind(null, -10).should.throw();

If you need to check something in an asynchronous function, you must do it 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

In case you are using something like Mocha, you should use an asynchronous test, and call done() in the proper place to make sure that your asynchronous function is called before the test finishes.

collection.findOne({ _id: 10 }, function(err, res) {
    if(err) return done(err);
    //second we test what you want


In general, if you need to check that something is executed, you are best using spies. A good example is sinon.


Asserts that .statusCode is code:


Not included in browser build.

.header(field[, value])

Asserts that a .headers object with field and optional value are present:

res.should.have.header('Content-Length', '123');

Not included in browser build.


Assert that Content-Type is "application/json; charset=utf-8"

Not included in browser build.


Assert that Content-Type is "text/html; charset=utf-8"

Not included in browser build.

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)

The methods that support this optional description are: eql, equal, within, instanceof, above, below, match, length, property, ownProperty.

Mocha example

For example you can use should with the Mocha test framework by simply including it:

var should = require('should');
var mylib = require('mylib');

describe('mylib', function() {
  it('should have a version with the format #.#.#', function() {


Actual list of contributors if you want to show it your friends.

To run the tests for should simply run:

$ make test



Yes, yes it does, with a single getter should, and no it won't break your code, because it does this properly with a non-enumerable property.


MIT © 2010-2014 TJ Holowaychuk

Jump to Line
Something went wrong with that request. Please try again.