Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 434 lines (320 sloc) 14.941 kb
434a42d @caolan added .swp file to fixtures to ensure file types other than .js and .cof...
caolan authored
1 Nodeunit
901300d @caolan added README
caolan authored
2 ========
3
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
4 Simple syntax, powerful tools. Nodeunit provides easy async unit testing for
5 node.js and the browser.
b250658 @caolan added some example images to the README and updated the intro
caolan authored
6
8c03725 @caolan updated README
caolan authored
7 * Simple to use
8 * Just export the tests from a module
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
9 * Works with node.js and in the browser.
8c03725 @caolan updated README
caolan authored
10 * Helps you avoid common pitfalls when testing asynchronous code
11 * Easy to add test cases with setUp and tearDown functions if you wish
efb2dc9 @caolan add a list of built-in reporters to the README
caolan authored
12 * Flexible reporters for custom output, built-in support for HTML and jUnit XML
8c03725 @caolan updated README
caolan authored
13 * Allows the use of mocks and stubs
ce2bcf2 @caolan added npm install command to README
caolan authored
14
3d73f4b @caolan added gerad to contributors
caolan authored
15 __Contributors__
16
05edbcf @caolan update contributor information
caolan authored
17 * [alexgorbatchev](https://github.com/alexgorbatchev)
18 * [alexkwolfe](https://github.com/alexkwolfe)
19 * [azatoth](https://github.com/azatoth)
20 * [coffeemate](https://github.com/coffeemate)
63657b4 @caolan updated contributor information
caolan authored
21 * [luebken](https://github.com/luebken)
c9a11e7 @caolan added orlandov to contributors
caolan authored
22 * [orlandov](https://github.com/orlandov)
05edbcf @caolan update contributor information
caolan authored
23 * [Sannis](https://github.com/Sannis)
24 * [sstephenson](https://github.com/sstephenson)
25 * [thegreatape](https://github.com/thegreatape)
26 * and thanks to [cjohansen](https://github.com/cjohansen) for input and advice
48a14cf @caolan added link to cjohansen's fork
caolan authored
27 on implementing setUp and tearDown functions. See
05edbcf @caolan update contributor information
caolan authored
28 [cjohansen's fork](https://github.com/cjohansen/nodeunit).
3d73f4b @caolan added gerad to contributors
caolan authored
29
05edbcf @caolan update contributor information
caolan authored
30 Also, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl)
0007d90 @caolan added link to gerad's nodeunit-dsl project
caolan authored
31 project, which implements a 'pretty dsl on top of nodeunit'.
32
cdcfccc @caolan link to CONTRIBUTORS.md file from README.md
caolan authored
33 More contributor information can be found in the
34 [CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md)
35 file.
59d62a0 @caolan moved detailed contribution info to the end of the README, since it was ...
caolan authored
36
901300d @caolan added README
caolan authored
37 Usage
38 -----
39
40 Here is an example unit test module:
41
42 exports.testSomething = function(test){
43 test.expect(1);
44 test.ok(true, "this assertion should pass");
45 test.done();
46 };
47
48 exports.testSomethingElse = function(test){
49 test.ok(false, "this assertion should fail");
50 test.done();
51 };
52
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
53 When run using the included test runner, this will output the following:
b250658 @caolan added some example images to the README and updated the intro
caolan authored
54
05edbcf @caolan update contributor information
caolan authored
55 <img src="https://github.com/caolan/nodeunit/raw/master/img/example_fail.png" />
b250658 @caolan added some example images to the README and updated the intro
caolan authored
56
8c03725 @caolan updated README
caolan authored
57 Installation
58 ------------
59
60 There are two options for installing nodeunit:
61
05edbcf @caolan update contributor information
caolan authored
62 1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit),
8c03725 @caolan updated README
caolan authored
63 then:
64
65 make && sudo make install
66
67 2. Install via npm:
68
69 npm install nodeunit
3e8710a @caolan minor updates to README
caolan authored
70
901300d @caolan added README
caolan authored
71 API Documentation
72 -----------------
73
8c03725 @caolan updated README
caolan authored
74 Nodeunit uses the functions available in the node.js
121df84 @azatoth fix assert module link to nodejs api docs
azatoth authored
75 [assert module](http://nodejs.org/docs/v0.4.2/api/assert.html):
8c03725 @caolan updated README
caolan authored
76
77 * __ok(value, [message])__ - Tests if value is a true value.
78 * __equal(actual, expected, [message])__ - Tests shallow, coercive equality
79 with the equal comparison operator ( == ).
80 * __notEqual(actual, expected, [message])__ - Tests shallow, coercive
81 non-equality with the not equal comparison operator ( != ).
82 * __deepEqual(actual, expected, [message])__ - Tests for deep equality.
83 * __notDeepEqual(actual, expected, [message])__ - Tests for any deep
84 inequality.
85 * __strictEqual(actual, expected, [message])__ - Tests strict equality, as
86 determined by the strict equality operator ( === )
87 * __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality,
88 as determined by the strict not equal operator ( !== )
89 * __throws(block, [error], [message])__ - Expects block to throw an error.
90 * __doesNotThrow(block, [error], [message])__ - Expects block not to throw an
91 error.
92 * __ifError(value)__ - Tests if value is not a false value, throws if it is a
93 true value. Useful when testing the first argument, error in callbacks.
94
95 Nodeunit also provides the following functions within tests:
901300d @caolan added README
caolan authored
96
8c03725 @caolan updated README
caolan authored
97 * __expect(amount)__ - Specify how many assertions are expected to run within a
98 test. Very useful for ensuring that all your callbacks and assertions are
99 run.
100 * __done()__ - Finish the current test function, and move on to the next. ALL
101 tests should call this!
901300d @caolan added README
caolan authored
102
8c03725 @caolan updated README
caolan authored
103 Nodeunit aims to be simple and easy to learn. This is achieved through using
cc2eabb @caolan updated README.md
caolan authored
104 existing structures (such as node.js modules) to maximum effect, and reducing
105 the API where possible, to make it easier to digest.
106
107 Tests are simply exported from a module, but they are still run in the order
8c03725 @caolan updated README
caolan authored
108 they are defined.
109
110 __Note:__ Users of old nodeunit versions may remember using ok, equals and same
111 in the style of qunit, instead of the assert functions above. These functions
112 still exist for backwards compatibility, and are simply aliases to their assert
113 module counterparts.
cc2eabb @caolan updated README.md
caolan authored
114
115
901300d @caolan added README
caolan authored
116 Asynchronous Testing
117 --------------------
118
cc2eabb @caolan updated README.md
caolan authored
119 When testing asynchronous code, there are a number of sharp edges to watch out
120 for. Thankfully, nodeunit is designed to help you avoid as many of these
121 pitfalls as possible. For the most part, testing asynchronous code in nodeunit
122 _just works_.
123
124
125 ### Tests run in series
901300d @caolan added README
caolan authored
126
cc2eabb @caolan updated README.md
caolan authored
127 While running tests in parallel seems like a good idea for speeding up your
128 test suite, in practice I've found it means writing much more complicated
129 tests. Because of node's module cache, running tests in parallel means mocking
130 and stubbing is pretty much impossible. One of the nicest things about testing
131 in javascript is the ease of doing stubs:
132
133 var _readFile = fs.readFile;
134 fs.readFile = function(path, callback){
135 // its a stub!
136 };
137 // test function that uses fs.readFile
138
139 // we're done
140 fs.readFile = _readFile;
141
142 You cannot do this when running tests in parallel. In order to keep testing as
143 simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run
144 fast anyway.
145
146
147 ### Explicit ending of tests
148
149 When testing async code its important that tests end at the correct point, not
150 just after a given number of assertions. Otherwise your tests can run short,
151 ending before all assertions have completed. Its important to detect too
152 many assertions as well as too few. Combining explicit ending of tests with
153 an expected number of assertions helps to avoid false test passes, so be sure
154 to use the test.expect() method at the start of your test functions, and
155 test.done() when finished.
901300d @caolan added README
caolan authored
156
157
22a8eea @caolan added support for nested tests and testCase
caolan authored
158 Groups, setUp and tearDown
159 --------------------------
160
161 Nodeunit allows the nesting of test functions:
162
163 exports.test1 = function (test) {
164 ...
165 }
166
167 exports.group = {
168 test2: function (test) {
169 ...
170 },
171 test3: function (test) {
172 ...
173 }
174 }
175
176 This would be run as:
177
178 test1
179 group - test2
180 group - test3
181
182 Using these groups its possible to add setUp and tearDown functions to your
8c03725 @caolan updated README
caolan authored
183 tests. Nodeunit has a utility function called testCase which allows you to
184 define a setUp function, which is run before each test, and a tearDown
185 function, which is run after each test calls test.done():
22a8eea @caolan added support for nested tests and testCase
caolan authored
186
187 var testCase = require('nodeunit').testCase;
188
189 module.exports = testCase({
43d7525 @caolan update setUp and tearDown examples in README
caolan authored
190 setUp: function (callback) {
22a8eea @caolan added support for nested tests and testCase
caolan authored
191 this.foo = 'bar';
43d7525 @caolan update setUp and tearDown examples in README
caolan authored
192 callback();
22a8eea @caolan added support for nested tests and testCase
caolan authored
193 },
43d7525 @caolan update setUp and tearDown examples in README
caolan authored
194 tearDown: function (callback) {
22a8eea @caolan added support for nested tests and testCase
caolan authored
195 // clean up
43d7525 @caolan update setUp and tearDown examples in README
caolan authored
196 callback();
22a8eea @caolan added support for nested tests and testCase
caolan authored
197 },
198 test1: function (test) {
199 test.equals(this.foo, 'bar');
200 test.done();
201 }
202 });
203
8c03725 @caolan updated README
caolan authored
204 In this way, its possible to have multiple groups of tests in a module, each
205 group with its own setUp and tearDown functions.
22a8eea @caolan added support for nested tests and testCase
caolan authored
206
207
901300d @caolan added README
caolan authored
208 Running Tests
209 -------------
210
434a42d @caolan added .swp file to fixtures to ensure file types other than .js and .cof...
caolan authored
211 Nodeunit comes with a basic command-line test runner, which can be installed
8c03725 @caolan updated README
caolan authored
212 using 'sudo make install'. Example usage:
901300d @caolan added README
caolan authored
213
781f9ab @caolan updated README to use command-line tool in examples
caolan authored
214 nodeunit testmodule1.js testfolder [...]
901300d @caolan added README
caolan authored
215
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
216 The default test reporter uses color output, because I think that's more fun :) I
217 intend to add a no-color option in future. To give you a feeling of the fun you'll
218 be having writing tests, lets fix the example at the start of the README:
b250658 @caolan added some example images to the README and updated the intro
caolan authored
219
05edbcf @caolan update contributor information
caolan authored
220 <img src="https://github.com/caolan/nodeunit/raw/master/img/example_pass.png" />
b250658 @caolan added some example images to the README and updated the intro
caolan authored
221
3e8710a @caolan minor updates to README
caolan authored
222 Ahhh, Doesn't that feel better?
b250658 @caolan added some example images to the README and updated the intro
caolan authored
223
cc2eabb @caolan updated README.md
caolan authored
224 When using the included test runner, it will exit using the failed number of
225 assertions as the exit code. Exiting with 0 when all tests pass.
226
901300d @caolan added README
caolan authored
227
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
228 ### Command-line Options
901300d @caolan added README
caolan authored
229
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
230 * __--reporter FILE__ - you can set the test reporter to a custom module or
231 on of the modules in nodeunit/lib/reporters, when omitted, the default test runner
232 is used.
44230d5 @Sannis Add --list-reporters option and reporters info string support
Sannis authored
233 * __--list-reporters__ - list available build-in reporters.
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
234 * __--config FILE__ - load config options from a JSON file, allows
235 the customisation of color schemes for the default test reporter etc. See
236 bin/nodeunit.json for current available options.
237 * __--version__ or __-v__ - report nodeunit version
238 * __--help__ - show nodeunit help
756d90b @caolan minor changes to README
caolan authored
239
901300d @caolan added README
caolan authored
240
50c52bd @caolan change title for browser section of README
caolan authored
241 Running tests in the browser
242 ----------------------------
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
243
244 Nodeunit tests can also be run inside the browser. For example usage, see
245 the examples/browser folder. The basic syntax is as follows:
246
247 __test.html__
248
249 <html>
250 <head>
2216937 @caolan update browser test runner to mirror qunit reports for now
caolan authored
251 <title>Example Test Suite</title>
252 <link rel="stylesheet" href="nodeunit.css" type="text/css" />
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
253 <script src="nodeunit.js"></script>
254 <script src="suite1.js"></script>
255 <script src="suite2.js"></script>
256 </head>
257 <body>
2216937 @caolan update browser test runner to mirror qunit reports for now
caolan authored
258 <h1 id="nodeunit-header>Example Test Suite</h1>
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
259 <script>
260 nodeunit.run({
2216937 @caolan update browser test runner to mirror qunit reports for now
caolan authored
261 'Suite One': suite1,
262 'Suite Two': suite2
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
263 });
264 </script>
265 </body>
266 </html>
267
268 Here, suite1 and suite2 are just object literals containing test functions or
269 groups, as would be returned if you did require('test-suite') in node.js:
270
271 __suite1.js__
272
273 this.suite1 = {
274 'example test': function (test) {
275 test.ok(true, 'everything is ok');
276 test.done();
277 }
278 };
279
280 If you wish to use a commonjs format for your test suites (using exports), it is
281 up to you to define the commonjs tools for the browser. There are a number of
282 alternatives and its important it fits with your existing code, which is
283 why nodeunit does not currently provide this out of the box.
284
285 In the example above, the tests will run when the page is loaded.
286
e6483f4 @caolan added note to README on browser build target
caolan authored
287 The browser-version of nodeunit.js is created in dist/browser when you do, 'make
288 browser'. You'll need [UglifyJS](https://github.com/mishoo/UglifyJS) installed in
289 order for it to automatically create nodeunit.min.js.
290
cd9bd21 @caolan updated README to include information on running tests in the browser
caolan authored
291
aeccae6 @caolan add an updated section on adding nodeunit to your projects to the README
caolan authored
292 Adding nodeunit to Your Projects
293 --------------------------------
294
295 If you don't want people to have to install the nodeunit command-line tool,
296 you'll want to create a script that runs the tests for your project with the
297 correct require paths set up. Here's an example test script, with a deps
298 directory containing the projects dependencies:
299
300 #!/usr/bin/env node
301 require.paths.unshift(__dirname + '/deps');
302
303 var reporter = require('nodeunit').reporters.default;
304 reporter.run(['test']);
305
306 If you're using git, you might find it useful to include nodeunit as a
307 submodule. Using submodules makes it easy for developers to download nodeunit
308 and run your test suite, without cluttering up your repository with
309 the source code. To add nodeunit as a git submodule do the following:
310
311 git submodule add git://github.com/caolan/nodeunit.git deps/nodeunit
312
313 This will add nodeunit to the deps folder of your project. Now, when cloning
314 the repository, nodeunit can be downloaded by doing the following:
315
316 git submodule init
317 git submodule update
318
319 Let's update the test script above with a helpful hint on how to get nodeunit,
320 if its missing:
321
322 #!/usr/bin/env node
323
324 require.paths.unshift(__dirname + '/deps');
325
326 try {
327 var reporter = require('nodeunit').reporters.default;
328 }
329 catch(e) {
330 var sys = require('sys');
331 sys.puts("Cannot find nodeunit module.");
332 sys.puts("You can download submodules for this project by doing:");
333 sys.puts("");
334 sys.puts(" git submodule init");
335 sys.puts(" git submodule update");
336 sys.puts("");
337 process.exit();
338 }
339
340 process.chdir(__dirname);
341 reporter.run(['test']);
342
343 Now if someone attempts to run your test suite without nodeunit installed they
344 will be prompted to download the submodules for your project.
345
346
efb2dc9 @caolan add a list of built-in reporters to the README
caolan authored
347 Built-in Test Reporters
348 -----------------------
349
350 * __default__ - The standard reporter seen in the nodeunit screenshots
351 * __minimal__ - Pretty, minimal output, shows errors and progress only
352 * __html__ - Outputs a HTML report to stdout
353 * __junit__ - Creates jUnit compatible XML reports, which can be used with
354 continuous integration tools such as [Hudson](http://hudson-ci.org/).
355
356
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
357 Writing a Test Reporter
901300d @caolan added README
caolan authored
358 ---------------------
359
434a42d @caolan added .swp file to fixtures to ensure file types other than .js and .cof...
caolan authored
360 Nodeunit exports runTest(fn, options), runModule(mod, options) and
901300d @caolan added README
caolan authored
361 runFiles(paths, options). You'll most likely want to run test suites from
362 files, which can be done using the latter function. The _options_ argument can
434a42d @caolan added .swp file to fixtures to ensure file types other than .js and .cof...
caolan authored
363 contain callbacks which run during testing. Nodeunit provides the following
901300d @caolan added README
caolan authored
364 callbacks:
365
366 * __moduleStart(name)__ - called before a module is tested
444f3d7 @caolan simplified api for testrunners
caolan authored
367 * __moduleDone(name, assertions)__ - called once all test functions within the
368 module have completed (see assertions object reference below)
901300d @caolan added README
caolan authored
369 ALL tests within the module
370 * __testStart(name)__ - called before a test function is run
444f3d7 @caolan simplified api for testrunners
caolan authored
371 * __testDone(name, assertions)__ - called once a test function has completed
372 (by calling test.done())
901300d @caolan added README
caolan authored
373 * __log(assertion)__ - called whenever an assertion is made (see assertion
374 object reference below)
444f3d7 @caolan simplified api for testrunners
caolan authored
375 * __done(assertions)__ - called after all tests/modules are complete
901300d @caolan added README
caolan authored
376
377 The __assertion__ object:
b883a9a @caolan fix formatting of assertion object methods in README
caolan authored
378
379 * __passed()__ - did the assertion pass?
380 * __failed()__ - did the assertion fail?
381 * __error__ - the AssertionError if the assertion failed
382 * __method__ - the nodeunit assertion method used (ok, same, equals...)
383 * __message__ - the message the assertion method was called with (optional)
901300d @caolan added README
caolan authored
384
781f9ab @caolan updated README to use command-line tool in examples
caolan authored
385 The __assertionList__ object:
444f3d7 @caolan simplified api for testrunners
caolan authored
386
387 * An array-like object with the following new attributes:
d2711ee @caolan Updated failures property to a method in README API docs
caolan authored
388 * __failures()__ - the number of assertions which failed
444f3d7 @caolan simplified api for testrunners
caolan authored
389 * __duration__ - the time taken for the test to complete in msecs
1e7b857 @caolan updated README to include new callback arguments
caolan authored
390
74c990a @caolan updated README to match recent changes to command line tool
caolan authored
391 For a reference implementation of a test reporter, see lib/reporters/default.js in
392 the nodeunit project directory.
901300d @caolan added README
caolan authored
393
394
cf2f529 @caolan documented the sandbox function
caolan authored
395 Sandbox utility
396 ---------------
397
398 This is a function which evaluates JavaScript files in a sandbox and returns the
399 context. The sandbox function can be used for testing client-side code or private
400 un-exported functions within a module.
401
402 var sandbox = require('nodeunit').utils.sandbox;
403 var example = sandbox('example.js');
404
405 __sandbox(files, sandbox)__ - Evaluates JavaScript files in a sandbox, returning
406 the context. The first argument can either be a single filename or an array of
407 filenames. If multiple filenames are given their contents are concatenated before
408 evalution. The second argument is an optional context to use for the sandbox.
409
410
901300d @caolan added README
caolan authored
411 Running the nodeunit Tests
412 --------------------------
413
3437a42 @caolan updated the nodeunit tests section of the README
caolan authored
414 The tests for nodeunit are written using nodeunit itself as the test framework.
415 However, the module test-base.js first does some basic tests using the assert
416 module to ensure that test functions are actually run, and a basic level of
417 nodeunit functionality is available.
901300d @caolan added README
caolan authored
418
e144ede @caolan added a Makefile for running tests and installing or uninstalling the co...
caolan authored
419 To run the nodeunit tests do:
420
421 make test
b65f83d @caolan added sstephenson to contributors and added note on broken tests when us...
caolan authored
422
e144ede @caolan added a Makefile for running tests and installing or uninstalling the co...
caolan authored
423 __Note:__ There was a bug in node v0.2.0 causing the tests to hang, upgrading
424 to v0.2.1 fixes this.
5ba6f99 @caolan added Sannis to contributors and added a note on coding style
caolan authored
425
426
427 Contributing
428 ------------
429
934a035 @Sannis Extract full contributors list into CONTRIBUTORS.md
Sannis authored
430 Contributions to the project are most welcome, so feel free to fork and improve.
431 When submitting a pull request, please run 'make lint' first to ensure
5ba6f99 @caolan added Sannis to contributors and added a note on coding style
caolan authored
432 we're following a consistent coding style.
433
Something went wrong with that request. Please try again.