Running unit tests in the browser

A guide to creating and running couchapp unit tests with nodeunit

You must be logged in to edit this page
I recommend you test using Node.js where possible. However, due to the nature of CouchApps you often end up having to write unit tests to run in the browser, either because they interact with browser APIs you don't want to mock or because you need to test it works in a range of browsers. When doing browser-based unit tests I use a few little Kanso packages I hacked together to automatically present an interface for running nodeunit test suites. It's a bit rough around the edges at the moment but gets the job done. __kanso.json__ Add nodeunit and nodeunit-testrunner packages to your kanso.json file and run kanso install to fetch them from the repositories. ```javascript { "name": "example", "version": "0.0.1", "description": "example app with unit tests", "modules": ["lib", "tests"], "load": "lib/app", "dependencies": { "modules": null, "properties": null, "nodeunit": null, "nodeunit-testrunner": null } } ``` Notice that I've included the 'tests' directory as a module path. Any modules dropped into that directory will be used as nodeunit test suites and displayed by the nodeunit-testrunner UI. __Rewrites__ You need to manually add the nodeunit-testrunner package's rewrites to your app, in my example that means editing lib/app.js to look like the following: ```javascript exports.rewrites = [ require('nodeunit-testrunner/rewrites') ]; ``` __Add some tests__ Assuming we have a module lib/foo.js that looks like this: ```javascript exports.hello = function (name) { return 'hello ' + name; }; ``` We could add a test by adding a module at tests/test-foo.js (this can be named anything so long as it's inside the tests directory). ```javascript var foo = require('lib/foo'); exports['test for foo.hello'] = function (test) { test.equal(foo.hello('bar'), 'hello bar'); test.done(); }; ``` If you then push your app and visit http://localhost:5984/example/\_design/example/\_rewrite/test in the browser you will be presented with a basic interface for running the test suites in the tests directory, either individually or all of them one after another.