Coder Social home page Coder Social logo

should.js's Introduction

should.js

should is an expressive, readable, test framework agnostic, assertion library for node.

It extends the Object prototype with a single non-enumerable getter that allows you to express how that object should behave.

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);
});

Installation

$ npm install should --save-dev

In browser

If you want to use should in browser, use version that is in root of repository. It is build with browserify (see Makefile about how it is build). To build fresh version:

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

chaining assertions

Every assertion will return a should.js-wraped Object, so assertions can be chained. For example:

user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');
user.pets.should.be.instanceof(Array).and.have.lengthOf(4);

All assertions return themselves but not property and ownProperty. They two would return the property value.

for example if a property is volatile we can first assert property existence:

// `user.should.have.property('pets')` returned `should(user.pets)` but not `should(user)`
user.should.have.property('pets').with.lengthOf(4)

which is essentially equivalent to below, however the property may not exist:

user.pets.should.have.lengthOf(4)

our dummy getters such as a, an, be, of and have make tests more readable while the getters and and with helps express chaining:

user.should.be.an.instanceOf(Object).and.have.property('name', 'tj')
user.should.have.property('pets').with.a.lengthOf(4)

Those getters don't have any actual effect, just for readability.

static

For some rare cases should can be used statically, without Object.prototype. It can be replacement for node assert module (and it uses the same AssertionError):

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)

ok

Assert truthfulness:

true.should.be.ok
'yay'.should.be.ok
(1).should.be.ok

or negated:

false.should.not.be.ok
''.should.not.be.ok
(0).should.not.be.ok

true

Assert === true:

true.should.be.true
'1'.should.not.be.true

false

Assert === false:

false.should.be.false
(0).should.not.be.false

arguments

Assert Arguments:

var args = (function(){ return arguments; })(1,2,3);
args.should.be.arguments;
[].should.not.be.arguments;

empty

Asserts that given object is empty

[].should.be.empty
''.should.be.empty
({}).should.be.empty
(function() {
  arguments.should.be.empty;
})()

eql

equality:

({ foo: 'bar' }).should.eql({ foo: 'bar' })
[1,2,3].should.eql([1,2,3])

equal and exactly

strict equality:

should.strictEqual(undefined, value)
should.strictEqual(false, value)
(4).should.equal(4)
'test'.should.equal('test')
[1,2,3].should.not.equal([1,2,3])
(4).should.be.exactly(4)

within

Assert inclusive numeric range:

user.age.should.be.within(5, 50)

approximately

Assert floating point number:

(99.99).should.be.approximately(100, 0.1);

type

Assert typeof:

user.should.be.type('object')
'test'.should.be.type('string')

instanceof and instanceOf

Assert instanceof or instanceOf:

user.should.be.an.instanceof(User)
[].should.be.an.instanceOf(Array)

above

Assert numeric value above the given value:

user.age.should.be.above(5)
user.age.should.not.be.above(100)

below

Assert numeric value below the given value:

user.age.should.be.below(100)
user.age.should.not.be.below(5)

NaN

Assert numeric valus is NaN:

(undefined + 0).should.be.NaN;

Infinity

Assert numeric valus is Infinity:

(1/0).should.be.Infinity;

match

Assert regexp match:

username.should.match(/^\w+$/)

length

Assert length property exists and has a value of the given number:

user.pets.should.have.length(5)
user.pets.should.have.a.lengthOf(5)
({ length: 10}).should.have.length(10);

Aliases: lengthOf

property

Assert property exists and has optional value(compare using ===):

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

Assert given properties exists:

user.should.have.properties('name', 'age');
user.should.have.properties(['name', 'age']);

ownProperty

Assert own property (on the immediate object):

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

status(code)

Asserts that .statusCode is code:

res.should.have.status(200);

header(field[, value])

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

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

json

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

res.should.be.json

html

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

res.should.be.html

include(obj) or contain(obj)

Assert that the given obj is present via indexOf(), so this works for strings, arrays, or custom objects implementing indexOf. Also it can assert if given object will have some sub-object.

Assert array value:

[1,2,3].should.include(3)
[1,2,3].should.include(2)
[1,2,3].should.not.include(4)

Assert substring:

'foo bar baz'.should.include('foo')
'foo bar baz'.should.include('bar')
'foo bar baz'.should.include('baz')
'foo bar baz'.should.not.include('FOO')

Assert object includes another object:

var tobi = { name: 'Tobi', age: 1 };
var jane = { name: 'Jane', age: 5 };
var user = { name: 'TJ', pet: tobi };

user.should.include({ pet: tobi });
user.should.include({ pet: tobi, name: 'TJ' });
user.should.not.include({ pet: jane });
user.should.not.include({ name: 'Someone' });

includeEql(obj)

Assert that an object equal to the given obj is present in an Array:

[[1],[2],[3]].should.includeEql([3])
[[1],[2],[3]].should.includeEql([2])
[[1],[2],[3]].should.not.includeEql([4])

throw()

Assert an exception is thrown:

(function(){
  throw new Error('fail');
}).should.throw();

Assert an exception is not thrown:

(function(){

}).should.not.throw();

Assert exception message matches string:

(function(){
  throw new Error('fail');
}).should.throw('fail');

Assert exepection message matches regexp:

(function(){
  throw new Error('failed to foo');
}).should.throw(/^fail/);

throwError()

An alias of throw, its purpose is to be an option for those who run jshint in strict mode.

(function(){
  throw new Error('failed to baz');
}).should.throwError(/^fail.*/);

startWith(str)

Assert that string starts with str.

'foobar'.should.startWith('foo')
'foobar'.should.not.startWith('bar')

endWith(str)

Assert that string ends with str.

'foobar'.should.endWith('bar')
'foobar'.should.not.endWith('foo')

keys

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']);

type assertions

({}).should.be.an.Object;
(1).should.be.an.Number;
[].should.be.an.Array;
(true).should.be.a.Boolean;
''.should.be.a.String;

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: expected 1 to equal 0 | 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, a, instanceof, above, below, match, length, property, ownProperty, include, and includeEql.

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() {
    lib.version.should.match(/^\d+\.\d+\.\d+$/);
  }
});

Running tests

To run the tests for should simply run:

$ make test

OMG IT EXTENDS OBJECT???!?!@

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.

License

(The MIT License)

Copyright (c) 2010-2011 TJ Holowaychuk <[email protected]>

Copyright (c) 2011 Aseem Kishore <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

should.js's People

Contributors

tj avatar btd avatar aseemk avatar gabrielfalcao avatar tootallnate avatar alsotang avatar alfred-nsh avatar fredr avatar theycallmeswift avatar nbrownus avatar mcandre avatar titarenko avatar dtao avatar eldargab avatar erkan-yilmaz avatar forbeslindesay avatar guileen avatar ichernev avatar seejohnrun avatar tvjg avatar meetwudi avatar lackac avatar msievers83 avatar rafmagana avatar raynos avatar rubenverborgh avatar tricknotes avatar skovalyov avatar travisjeffery avatar ulikoehler avatar

Watchers

 avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.