source: Dev/trunk/node_modules/should/Readme.md @ 536

Last change on this file since 536 was 516, checked in by hendrikvanantwerpen, 11 years ago

Enable deployment with Grunt.

File size: 11.5 KB
Line 
1# should.js
2
3_should_ is an expressive, readable, test framework agnostic, assertion library for [node](http://nodejs.org).
4
5It extends the Object prototype with a single non-enumerable getter that allows you to express how that object should behave.
6
7## Example
8```javascript
9var should = require('should');
10
11var user = {
12    name: 'tj'
13  , pets: ['tobi', 'loki', 'jane', 'bandit']
14};
15
16user.should.have.property('name', 'tj');
17user.should.have.property('pets').with.lengthOf(4);
18
19// or without Object.prototype, for guys how did Object.create(null)
20should(user).have.property('name', 'tj');
21should(true).ok;
22
23someAsyncTask(foo, function(err, result){
24  should.not.exist(err);
25  should.exist(result);
26  result.bar.should.equal(foo);
27});
28```
29## Installation
30
31    $ npm install should --save-dev
32
33## In browser
34
35If you want to use _should_ in browser, use version that is in root of repository. It is build with browserify (see [Makefile](https://github.com/visionmedia/should.js/blob/master/Makefile) about how it is build). To build fresh version:
36
37```bash
38# you should have browserify
39npm install -g browserify
40make browser
41```
42
43## chaining assertions
44
45Every assertion will return a should.js-wraped Object, so assertions can be chained. For example:
46
47```js
48user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');
49user.pets.should.be.instanceof(Array).and.have.lengthOf(4);
50```
51
52All assertions return themselves but not `property` and `ownProperty`. They two would return the property value.
53
54for example if a property is volatile we can first assert property existence:
55```javascript
56// `user.should.have.property('pets')` returned `should(user.pets)` but not `should(user)`
57user.should.have.property('pets').with.lengthOf(4)
58```
59which is essentially equivalent to below, however the property may not exist:
60```javascript
61user.pets.should.have.lengthOf(4)
62```
63
64our dummy getters such as _a_, _an_, _be_, _of_ and _have_ make tests more readable while the getters _and_ and _with_ helps express chaining:
65```javascript
66user.should.be.an.instanceOf(Object).and.have.property('name', 'tj')
67user.should.have.property('pets').with.a.lengthOf(4)
68```
69Those getters don't have any actual effect, just for readability.
70
71## static
72
73For some rare cases should can be used statically, without `Object.prototype`.
74It can be replacement for node assert module (and it uses the same `AssertionError`):
75
76```javascript
77assert.fail(actual, expected, message, operator) // just write wrong should assertion
78assert(value, message), assert.ok(value, [message]) // should(value).ok
79assert.equal(actual, expected, [message]) // should(actual).eql(expected, [message])
80assert.notEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])
81assert.deepEqual(actual, expected, [message]) // should(actual).eql(expected, [message])
82assert.notDeepEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])
83assert.strictEqual(actual, expected, [message]) // should(actual).equal(expected, [message])
84assert.notStrictEqual(actual, expected, [message]) // should(actual).not.equal(expected, [message])
85assert.throws(block, [error], [message]) // should(block).throw([error])
86assert.doesNotThrow(block, [message]) // should(block).not.throw([error])
87assert.ifError(value) // should(value).Error (to check if it is error) or should(value).not.ok (to check that it is falsy)
88```
89
90## ok
91
92Assert truthfulness:
93```javascript
94true.should.be.ok
95'yay'.should.be.ok
96(1).should.be.ok
97```
98or negated:
99```javascript
100false.should.not.be.ok
101''.should.not.be.ok
102(0).should.not.be.ok
103```
104## true
105
106Assert === true:
107```javascript
108true.should.be.true
109'1'.should.not.be.true
110```
111## false
112
113Assert === false:
114```javascript
115false.should.be.false
116(0).should.not.be.false
117```
118## arguments
119
120Assert `Arguments`:
121```javascript
122var args = (function(){ return arguments; })(1,2,3);
123args.should.be.arguments;
124[].should.not.be.arguments;
125```
126## empty
127
128Asserts that given object is empty
129```javascript
130[].should.be.empty
131''.should.be.empty
132({}).should.be.empty
133(function() {
134  arguments.should.be.empty;
135})()
136```
137## eql
138
139equality:
140```javascript
141({ foo: 'bar' }).should.eql({ foo: 'bar' })
142[1,2,3].should.eql([1,2,3])
143```
144## equal and exactly
145
146strict equality:
147```javascript
148should.strictEqual(undefined, value)
149should.strictEqual(false, value)
150(4).should.equal(4)
151'test'.should.equal('test')
152[1,2,3].should.not.equal([1,2,3])
153(4).should.be.exactly(4)
154```
155## within
156
157Assert inclusive numeric range:
158```javascript
159user.age.should.be.within(5, 50)
160```
161## approximately
162
163Assert floating point number:
164```javascript
165(99.99).should.be.approximately(100, 0.1);
166```
167## type
168
169Assert __typeof__:
170```javascript
171user.should.be.type('object')
172'test'.should.be.type('string')
173```
174## instanceof and instanceOf
175
176Assert __instanceof__ or __instanceOf__:
177```javascript
178user.should.be.an.instanceof(User)
179[].should.be.an.instanceOf(Array)
180```
181## above
182
183Assert numeric value above the given value:
184```javascript
185user.age.should.be.above(5)
186user.age.should.not.be.above(100)
187```
188## below
189
190Assert numeric value below the given value:
191```javascript
192user.age.should.be.below(100)
193user.age.should.not.be.below(5)
194```
195## NaN
196
197Assert numeric valus is NaN:
198```javascript
199(undefined + 0).should.be.NaN;
200```
201## Infinity
202
203Assert numeric valus is Infinity:
204```javascript
205(1/0).should.be.Infinity;
206```
207## match
208
209Assert regexp match:
210```javascript
211username.should.match(/^\w+$/)
212```
213## length
214
215Assert _length_ property exists and has a value of the given number:
216```javascript
217user.pets.should.have.length(5)
218user.pets.should.have.a.lengthOf(5)
219({ length: 10}).should.have.length(10);
220```
221Aliases: _lengthOf_
222
223## property
224
225Assert property exists and has optional value(compare using `===`):
226```javascript
227user.should.have.property('name')
228user.should.have.property('age', 15)
229user.should.not.have.property('rawr')
230user.should.not.have.property('age', 0)
231```
232
233## properties
234
235Assert given properties exists:
236```javascript
237user.should.have.properties('name', 'age');
238user.should.have.properties(['name', 'age']);
239```
240## ownProperty
241
242Assert own property (on the immediate object):
243```javascript
244({ foo: 'bar' }).should.have.ownProperty('foo')
245```
246## status(code)
247
248 Asserts that `.statusCode` is `code`:
249```javascript
250res.should.have.status(200);
251```
252## header(field[, value])
253
254 Asserts that a `.headers` object with `field` and optional `value` are present:
255```javascript
256res.should.have.header('content-length');
257res.should.have.header('Content-Length', '123');
258res.should.have.header('content-length', '123');
259```
260## json
261
262  Assert that Content-Type is "application/json; charset=utf-8"
263```javascript
264res.should.be.json
265```
266## html
267
268  Assert that Content-Type is "text/html; charset=utf-8"
269```javascript
270res.should.be.html
271```
272
273## include(obj) or contain(obj)
274
275Assert 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.
276
277Assert array value:
278```javascript
279[1,2,3].should.include(3)
280[1,2,3].should.include(2)
281[1,2,3].should.not.include(4)
282```
283Assert substring:
284```javascript
285'foo bar baz'.should.include('foo')
286'foo bar baz'.should.include('bar')
287'foo bar baz'.should.include('baz')
288'foo bar baz'.should.not.include('FOO')
289```
290Assert object includes another object:
291```javascript
292var tobi = { name: 'Tobi', age: 1 };
293var jane = { name: 'Jane', age: 5 };
294var user = { name: 'TJ', pet: tobi };
295
296user.should.include({ pet: tobi });
297user.should.include({ pet: tobi, name: 'TJ' });
298user.should.not.include({ pet: jane });
299user.should.not.include({ name: 'Someone' });
300```
301## includeEql(obj)
302
303Assert that an object equal to the given `obj` is present in an Array:
304```javascript
305[[1],[2],[3]].should.includeEql([3])
306[[1],[2],[3]].should.includeEql([2])
307[[1],[2],[3]].should.not.includeEql([4])
308```
309## throw()
310
311Assert an exception is thrown:
312
313```js
314(function(){
315  throw new Error('fail');
316}).should.throw();
317```
318
319Assert an exception is not thrown:
320
321```js
322(function(){
323
324}).should.not.throw();
325```
326Assert exception message matches string:
327
328```js
329(function(){
330  throw new Error('fail');
331}).should.throw('fail');
332```
333
334Assert exepection message matches regexp:
335
336```js
337(function(){
338  throw new Error('failed to foo');
339}).should.throw(/^fail/);
340```
341
342## throwError()
343
344An alias of `throw`, its purpose is to be an option for those who run
345[jshint](https://github.com/jshint/node-jshint/) in strict mode.
346
347```js
348(function(){
349  throw new Error('failed to baz');
350}).should.throwError(/^fail.*/);
351```
352
353## startWith(str)
354
355Assert that string starts with `str`.
356
357```javascript
358'foobar'.should.startWith('foo')
359'foobar'.should.not.startWith('bar')
360```
361## endWith(str)
362
363Assert that string ends with `str`.
364
365```javascript
366'foobar'.should.endWith('bar')
367'foobar'.should.not.endWith('foo')
368```
369
370## keys
371
372Assert own object keys, which must match _exactly_,
373and will fail if you omit a key or two:
374
375    var obj = { foo: 'bar', baz: 'raz' };
376    obj.should.have.keys('foo', 'baz');
377    obj.should.have.keys(['foo', 'baz']);
378
379## type assertions
380
381```javascript
382({}).should.be.an.Object;
383(1).should.be.an.Number;
384[].should.be.an.Array;
385(true).should.be.a.Boolean;
386''.should.be.a.String;
387```
388
389## Optional Error description
390
391As 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:
392
393    (1).should.eql(0, 'some useful description')
394
395    AssertionError: expected 1 to equal 0 | some useful description
396      at Object.eql (/Users/swift/code/should.js/node_modules/should/lib/should.js:280:10)
397      ...
398
399The methods that support this optional description are: `eql`, `equal`, `within`, `a`, `instanceof`, `above`, `below`, `match`, `length`, `property`, `ownProperty`, `include`, and `includeEql`.
400
401## Mocha example
402
403For example you can use should with the [Mocha test framework](http://visionmedia.github.io/mocha/) by simply including it:
404
405```javascript
406var should = require('should');
407var mylib = require('mylib');
408
409
410describe('mylib', function () {
411  it('should have a version with the format #.#.#', function() {
412    lib.version.should.match(/^\d+\.\d+\.\d+$/);
413  }
414});
415```
416
417## Running tests
418
419To run the tests for _should_ simply run:
420
421    $ make test
422
423## OMG IT EXTENDS OBJECT???!?!@
424
425Yes, 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.
426
427## License
428
429(The MIT License)
430
431Copyright (c) 2010-2011 TJ Holowaychuk <tj@vision-media.ca>
432
433Copyright (c) 2011 Aseem Kishore <aseem.kishore@gmail.com>
434
435Permission is hereby granted, free of charge, to any person obtaining
436a copy of this software and associated documentation files (the
437'Software'), to deal in the Software without restriction, including
438without limitation the rights to use, copy, modify, merge, publish,
439distribute, sublicense, and/or sell copies of the Software, and to
440permit persons to whom the Software is furnished to do so, subject to
441the following conditions:
442
443The above copyright notice and this permission notice shall be
444included in all copies or substantial portions of the Software.
445
446THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
447EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
448MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
449IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
450CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
451TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
452SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note: See TracBrowser for help on using the repository browser.