Fork me on GitHub

doctest.js by Ian Bicking

Doctest.js: examples

Web Service

You can use doctest.js to test APIs; in fact, it's reasonable to use it for acceptance tests of the web APIs themselves, not just to test the Javascript wrappers around those APIs.
In this example we'll access the Geonames API. First we'll want some routines to help us later on. You could put these into a separate .js file and include it, but often (especially in an example ;) it's best to be fully transparent and list all the routines out in the open...
$ apiLocation = 'http://ws.geonames.org/';
$ function query(endpoint, q) {
>   var url = apiLocation + endpoint;
>   jQuery.ajax({
>     url: url,
>     data: q,
>     dataType: "json",
>     success: Spy('success', {wait: true, ignoreThis: true}),
>     error: Spy('error')
>   });
> }
Some things to notice about this example:
  • apiLocation is hard coded, but you could read it from the query string, allowing something like test.html?apiLocation=http://localhost:8080.
  • We create a Spy for both success and failure, as we want to track both of these. We could just use functions, but mostly there's an advantage to being able to watch .called. If you used {writes: true} you might not need the .applies functions.
  • wait can be called from anywhere. That means when you call this function doctest will wait until something is called, and will test all the output since that time (either the success or failure writeln()). Timeout is the other possibility.
Now we'll use the routine to actually run a test:
$ query('postalCodeSearchJSON', {postalcode: 9011, maxRows: 5});
success({
  postalCodes: [
    {...}
  ]
}, ...)

Web Service/XML

What we do for JSON, we can also do for XML; in this case it's just fetching a static XML Atom document.
$ $.ajax({
>   url: './.resources/example.xml',
>   dataType: 'xml',
>   success: function (doc) {
>     gdoc = doc;
>     writeln(repr(doc));
>   },
>   error: Spy('error')
> });
$ wait(0.5);
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Example Feed</title>
  ...
</feed>

Download

You can download this project in either zip or tar formats.

You can also clone the project with Git by running:

$ git clone git://github.com/ianb/doctestjs