<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>cjohansen.no</title>
    <link>http://www.cjohansen.no</link>
    <description>
       A blog on programing, web and movies
    </description>
    <atom:link href="http://www.cjohansen.no/rss.xml" rel="self" type="application/rss+xml" />
    <language>no-nb</language>
    <copyright>Copyright 2006-2015 Christian Johansen</copyright>
                <item>
  <pubDate>02 Jan 2012 14:16:29 GMT</pubDate>
  <title>Sinon.JS 1.3.0 out now</title>
  <link>http://www.cjohansen.no/en/sinon_js/sinon_js_1_3_0_out_now</link>
  <guid>http://www.cjohansen.no/en/sinon_js/sinon_js_1_3_0_out_now</guid>
  <comments>http://www.cjohansen.no/en/sinon_js/sinon_js_1_3_0_out_now#comments</comments>
  <description>
    
&lt;p&gt;
On this second day of 2012, I am happy to announce Sinon.JS 1.3.0, the latest and greatest in JavaScript test spies, stubs and mocks.
&lt;/p&gt;

    
&lt;p&gt;
As always, Sinon.JS honors 			
									&lt;a href=&quot;http://semver.org&quot;&gt;semantic versioning&lt;/a&gt;, meaning that if your code works with 1.0, 1.1. and/or 1.2, 1.3.0 is a drop-in replacement. Eager? 			
									&lt;a href=&quot;http://sinonjs.org&quot;&gt;get your copy right away&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_1&quot;&gt;Fake XMLHttpRequests and the server&lt;/h2&gt;
&lt;p&gt;
The fake XHRs and server in Sinon are useful both for testing and for quick mockups. Sinon 1.3.0 includes a few improvements targeted at the mockup use case.
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_1_1&quot;&gt;Fake server logic&lt;/h3&gt;
&lt;p&gt;
This feature was actually introduced earlier, but slightly flawed. You can now use a bare function handler with 				&lt;code&gt;server.respondWith&lt;/code&gt;. If the function calls 				&lt;code&gt;respond&lt;/code&gt; on the passed in 				&lt;code&gt;xhr&lt;/code&gt; object, no further processing will occur. If it does not, the next handler will be consulted as usual:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;// Log each request in the console,
// like e.g. Firebug already does for normal requests

var server = sinon.fakeServer.create();
server.respondWith(function (xhr) {
    console.log(xhr.method, xhr.url, xhr.requestBody);
});

// Another handler that responds to all POSTs to /rest/*
// by sending back the POST body.
server.respondWith(function (xhr) {
    if (xhr.method == &amp;quot;POST&amp;quot; &amp;amp;&amp;amp; /^\/rest\//.test(xhr.url)) {
        xhr.respond(200, {}, xhr.requestBody);
    }
});&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc326619_1_2&quot;&gt;Partially faked servers&lt;/h3&gt;
&lt;p&gt;
When using Sinon for mockup development, or integration testing, you might want some requests to be faked out and others go through to the backend server. With request filters you can:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.FakeXMLHttpRequest.useFilters = true;
sinon.FakeXMLHttpRequest.addFilter(function (method, url, async, username, password) {
    // Don't fake POST requests
    if (method == &amp;quot;POST&amp;quot;) {
        return true;
    }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
			
									&lt;a href=&quot;http://sinonjs.org/docs/#filtered-requests&quot;&gt;More details in the docs&lt;/a&gt;. This feature was implemented by Tim Ruffles. Thanks Tim!
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_1_3&quot;&gt;Quick and dirty responds&lt;/h3&gt;
&lt;p&gt;
When your fake server only has one pre-configured response, you can now pass your 				&lt;code&gt;respondWith&lt;/code&gt; arguments directly to 				&lt;code&gt;respond&lt;/code&gt; to do both in one call:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;server.respond(&amp;quot;GET&amp;quot;, &amp;quot;/hello&amp;quot;, [&amp;quot;OK&amp;quot;]);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This feature was implemented by Gavin Huang, thanks Gavin!
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_2&quot;&gt;Spies&lt;/h2&gt;
&lt;p&gt;
Test spies beefed up slightly in 1.3.0.
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_2_1&quot;&gt;More transparent spies&lt;/h3&gt;
&lt;p&gt;
Test spies now properly mirrors any properties set on the function prior to spying:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var api = {
    doIt: function () {
        api.doIt.times += 1;
        alert(&amp;quot;Called &amp;quot; + api.doIt.times + &amp;quot; times&amp;quot;);
    }
};

api.doIt.times = 0;

api.doIt();
sinon.spy(api, &amp;quot;doIt&amp;quot;);
console.log(api.doIt.times); // &amp;quot;1&amp;quot;&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc326619_2_2&quot;&gt;New properties&lt;/h3&gt;
&lt;p&gt;
Some properties where added to more conveniently get at specific calls: 				&lt;code&gt;spy.firstCall&lt;/code&gt;, 				&lt;code&gt;spy.secondCall&lt;/code&gt;, 				&lt;code&gt;spy.thirdCall&lt;/code&gt;, 				&lt;code&gt;spy.lastCall&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Maximilian Antoni added these properties, thanks Max!
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_2_3&quot;&gt;Spy and stub inherited methods&lt;/h3&gt;
&lt;p&gt;
Thanks to Felix Geisendörfer and Robin Mehner, who both convinced me in 			
									&lt;a href=&quot;https://github.com/cjohansen/Sinon.JS/pull/54&quot;&gt;this discussion&lt;/a&gt; - and Felix in particular who took it upon him to implement it - Sinon will now gladly spy on and stub inherited methods (i.e. non-own-properties).
&lt;/p&gt;

&lt;p&gt;
In previous versions, this was specifically prohibited to avoid allowing you to spy on methods that did not exist. I still believe this is and important measure to avoid mismatches between tests and integrated production code, but restricting inherited properties was ultimately not helpful.
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_3&quot;&gt;Stubs&lt;/h2&gt;	&lt;h3 id=&quot;toc326619_3_1&quot;&gt;Calling callbacks&lt;/h3&gt;
&lt;p&gt;
Maximilian Antoni has been busy in this version of Sinon. He also implemented some very useful methods for stubs. Whenever you have a stub that takes function arguments, you may want to be able to call those callbacks in your tests.
&lt;/p&gt;

&lt;p&gt;
Sinon has enabled this for a while using 				&lt;code&gt;stub.yields(42)&lt;/code&gt;. The problem however, is that this must be specified up-front in a mock-like way. If you don't like the Yoda-touch of the mock, you might want to explicitly invoke callbacks after the fact instead. Now you can, using 				&lt;code&gt;stub.yield()&lt;/code&gt;, 				&lt;code&gt;stub.yieldTo()&lt;/code&gt;, 				&lt;code&gt;stub.callArg()&lt;/code&gt; and 				&lt;code&gt;stub.callArgWith()&lt;/code&gt;.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var stub = sinon.stub();
stub(42, function () {
    console.log(&amp;quot;Yeah!&amp;quot;);
});

stub.yield(); // Prints &amp;quot;Yeah!&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
See 			
									&lt;a href=&quot;http://sinonjs.org/docs/#stubs-api&quot;&gt;the docs&lt;/a&gt; for more details.
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_3_2&quot;&gt;Returning an argument&lt;/h3&gt;
&lt;p&gt;
It can be useful to tell a stub to return one of its arguments, rather than a pre-configured static value. Thanks to Gavin Huang, you now can:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var stub = sinon.stub().returnsArg(2);
stub(1, 2, 3); // Returns 3&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc326619_4&quot;&gt;Error messages&lt;/h2&gt;
&lt;p&gt;
Sinon 1.3.0 has improved debugability on two major accounts.
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_4_1&quot;&gt;Error logging&lt;/h3&gt;
&lt;p&gt;
Sinon will now log certain exceptions to 				&lt;code&gt;sinon.log&lt;/code&gt;. This method is intended to be overridden - by default it does nothing. By setting it to something that prints in your environment, you can gain more insight in what happens when things fail inside Sinon:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;// Using Buster.JS
sinon.log = function () {
    buster.log.apply(buster, arguments);
};

// Using JsTestDriver
sinon.log = function () {
    jstestdriver.console.log.apply(jstestdriver.console, arguments);
};

// In-browser stuff
sinon.log = function () {
    console.log.apply(console, arguments);
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The suggested fix for Buster will be default in the next release of Buster.
&lt;/p&gt;
	&lt;h3 id=&quot;toc326619_4_2&quot;&gt;Object formatting&lt;/h3&gt;
&lt;p&gt;
The default bundle found on the website now uses 			
									&lt;a href=&quot;http://gitorious.org/buster/buster-format&quot;&gt;buster-format&lt;/a&gt; to nicely format objects in various error messages. For instance, previously 				&lt;code&gt;sinon.assert.calledWith(spy, obj)&lt;/code&gt; would print something like 				&lt;code&gt;&amp;quot;expected [object Object]&amp;quot;&lt;/code&gt;, while now it will print a pretty string representation of the object.
&lt;/p&gt;

&lt;p&gt;
It backed down from making buster-format a dependency in the last moment, because I don't want Sinon to have dependencies. This means that you don't get this feature for free on Node. buster-format will be used if it's installed in your project, otherwise, Sinon will format with 				&lt;code&gt;util.inspect&lt;/code&gt;, which for the most part is just as nice.
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_5&quot;&gt;Bug fixes&lt;/h2&gt;
&lt;p&gt;
Like always, the new release also includes various bug fixes, by me and others. See the 			
									&lt;a href=&quot;http://sinonjs.org/Changelog.txt&quot;&gt;Changelog&lt;/a&gt; for details.
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_6&quot;&gt;Contributors&lt;/h2&gt;
&lt;p&gt;
This release welcomes 5 new contributors, bringing the total number of authors up to 15. The 			
									&lt;a href=&quot;https://github.com/cjohansen/Sinon.JS/network/members&quot;&gt;GitHub community&lt;/a&gt; and watchers are also growing. I'm very thankful to have so many nice people enthustiastically contribute to this project. I want to thank you all for helping keeping Sinon awesome through bug reports, pull requests, discussions/challenges and helping others use Sinon!
&lt;/p&gt;
	&lt;h2 id=&quot;toc326619_7&quot;&gt;What's in Sinon's future?&lt;/h2&gt;
&lt;p&gt;
I have already tagged 			
									&lt;a href=&quot;https://github.com/cjohansen/Sinon.JS/issues&quot;&gt;two issues&lt;/a&gt; on the Sinon 1.4.0 milestone, even though I don't know when it will be out. 1.4.0 will include a 				&lt;code&gt;fakeServer&lt;/code&gt; that works with the same interface on Node, and some new matchers to provide a wider variety of matching functionality (e.g. check if stub was called with a string and a number, as opposed to exact values).
&lt;/p&gt;

&lt;p&gt;
If you have suggestions/requests, please report them in the issue tracker. I will be busy with/prioritizing 			
									&lt;a href=&quot;http://busterjs.org&quot;&gt;Buster.JS&lt;/a&gt; for the foreseeable future, so I don't know when new Sinon features will land. I aim to do 1.4.0 sometime before the summer, and do patch-releases with bug fixes more frequently than in the past (basically, I'll finally get my shit together and start using branches actively for this project).
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>03 Aug 2011 00:44:28 GMT</pubDate>
  <title>An introduction to Emacs Lisp</title>
  <link>http://www.cjohansen.no/en/emacs/an_introduction_to_emacs_lisp</link>
  <guid>http://www.cjohansen.no/en/emacs/an_introduction_to_emacs_lisp</guid>
  <comments>http://www.cjohansen.no/en/emacs/an_introduction_to_emacs_lisp#comments</comments>
  <description>
    
&lt;p&gt;
As a long-time passionate Emacs user, I've been curious about Lisp in general and Emacs Lisp in particular for quite some time. Until recently I had not written any Lisp apart from my .emacs.d setup, despite having read both An introduction to programming in Emacs Lisp and The Little Schemer last summer. A year later, I have finally written some Lisp, and I thought I'd share the code as an introduction to others out there curious about Lisp and extending Emacs.
&lt;/p&gt;

&lt;p&gt;
			
									&lt;a href=&quot;http://cjohansen.no/an-introduction-to-elisp&quot;&gt;Read full article&lt;/a&gt;.
&lt;/p&gt;

    
&lt;p&gt;
(Sorry for the clunky link indirection - I've started the progress of moving my blog off this overkill CMS to simple HTML files). 			
									&lt;a href=&quot;http://cjohansen.no/an-introduction-to-elisp&quot;&gt;Read full article&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>05 May 2011 22:16:33 GMT</pubDate>
  <title>Sinon.JS 1.1.0 out now</title>
  <link>http://www.cjohansen.no/en/sinon_js/sinon_js_1_1_0_out_now</link>
  <guid>http://www.cjohansen.no/en/sinon_js/sinon_js_1_1_0_out_now</guid>
  <comments>http://www.cjohansen.no/en/sinon_js/sinon_js_1_1_0_out_now#comments</comments>
  <description>
    
&lt;p&gt;
Boy, time passes by quickly. I started writing Sinon.JS while writing 			
									&lt;a href=&quot;http://tddjs.com&quot;&gt;my book on TDD with JavaScript&lt;/a&gt;, and in just a month, Sinon.JS has celebrates its first birthday (0.5.0 was released June 9th 2010). Today I am happy to announce Sinon.JS 1.1.0, the first significant update since 1.0.0, released last December. In this post I'll take you through what's new and exciting in 1.1.0.
&lt;/p&gt;

    
&lt;p&gt;
As always, Sinon.JS honors 			
									&lt;a href=&quot;http://semver.org&quot;&gt;semantic versioning&lt;/a&gt;, meaning that if your code works with 1.0.x, 1.1.0 is a drop-in replacement. Eager? 			
									&lt;a href=&quot;http://sinonjs.org&quot;&gt;get your copy right away&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_1&quot;&gt;Bug fixes&lt;/h2&gt;
&lt;p&gt;
Sinon.JS is just another project to show that properly testing your code pays off. Very few bugs have been filed, even with quite widespread use. I personally use Sinon.JS almost daily, and have stumbled upon very few problems. Still, a few minor issues have been sorted out, and Sinon.JS is now more bullet proof than ever.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_2&quot;&gt;Spies&lt;/h2&gt;
&lt;p&gt;
Spies have gained one important new method: 				&lt;code&gt;withArgs&lt;/code&gt;. This little gem allows you to create a spy that will only record calls for a specific set of arguments. This is mildly useful for spies, but as you will see, when stubs inherit this method it gets really interesting.
&lt;/p&gt;

&lt;p&gt;
Here is how you would use it with spies:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should call method once with each argument&amp;quot;: function () {
    var object = { method: function () {} };
    var spy = sinon.spy(object, &amp;quot;method&amp;quot;);
    spy.withArgs(42);
    spy.withArgs(1);

    object.method(42);
    object.method(1);

    assert(spy.withArgs(42).calledOnce);
    assert(spy.withArgs(1).calledOnce);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
If you call 				&lt;code&gt;withArgs&lt;/code&gt; on the same spy with the same arguments multiple times, you always get the same spy, which allows for the expressive syntax seen in the example above. 				&lt;code&gt;withArgs&lt;/code&gt; also returns a new spy that supports the 			
									&lt;a href=&quot;http://sinonjs.org/docs/#spies&quot;&gt;full spy API&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_3&quot;&gt;Stubs&lt;/h2&gt;	&lt;h3 id=&quot;toc231331_3_1&quot;&gt;withArgs&lt;/h3&gt;
&lt;p&gt;
Because stubs inherit the full spy API, they also gained the new 				&lt;code&gt;withArgs&lt;/code&gt; method. This adds a sorely missed feature in Sinon.JS: the ability to cause a stub to behave differently in response to different input.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should stub method differently based on arguments&amp;quot;: function () {
    var callback = sinon.stub();
    callback.withArgs(42).returns(1);
    callback.withArgs(1).throws(&amp;quot;TypeError&amp;quot;);

    callback(); // No return value, no exception
    callback(42); // Returns 1
    callback(1); // Throws TypeError
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The arguments can be any value of course, not just numbers.
&lt;/p&gt;
	&lt;h3 id=&quot;toc231331_3_2&quot;&gt;yields and yieldsTo&lt;/h3&gt;
&lt;p&gt;
Callbacks are not exactly uncommon in JavaScript. Stubs have supported the 				&lt;code&gt;callsArg&lt;/code&gt; and 				&lt;code&gt;callsArgWith&lt;/code&gt; methods almost since the beginning to help with automatically invoking callbacks passed to stubs. With 1.1.0, there are two new methods that make this slightly prettier, and slightly less implementation specific.
&lt;/p&gt;

&lt;p&gt;
The 				&lt;code&gt;yields([arg1, arg2, ...])&lt;/code&gt; method will invoke the first callback passed to the stub with the given arguments (if any). This means you no longer have to specify the argument index at which the callback can be found. It's a little bit of magic, but it is based on the fact that most callback based APIs accept a single callback somewhere among the arguments.
&lt;/p&gt;

&lt;p&gt;
Here's an example of using the new method:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var todoList = {
    getItem: function (id, callback) {
        // ...
    }
};

&amp;quot;test should do something when the callback is called&amp;quot;: function () {
    sinon.stub(todoList, &amp;quot;getItem&amp;quot;).yields({ id: 1, text: &amp;quot;Something&amp;quot;, isDone: false });

    todoList.getItem(1, function (item) {
        assertEquals(item, { id: 1, text: &amp;quot;Something&amp;quot;, isDone: false });
    });
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Obviously, testing that a stub behaves as configured is just silly, but you get the point.
&lt;/p&gt;

&lt;p&gt;
A related method is 				&lt;code&gt;yieldsTo&lt;/code&gt;. It works like 				&lt;code&gt;yields&lt;/code&gt;, only it calls a callback received as a property on an object argument. You provide the property name, and Sinon.JS finds the right object:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should fake successful ajax request&amp;quot;: function () {
    sinon.stub(jQuery, &amp;quot;ajax&amp;quot;).yieldsTo(&amp;quot;success&amp;quot;, [1, 2, 3]);

    jQuery.ajax({
        success: function (data) {
            assertEquals([1, 2, 3], data);
        }
    });
}&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc231331_3_3&quot;&gt;Sandboxed stubs&lt;/h3&gt;
&lt;p&gt;
When using the 				&lt;code&gt;stub&lt;/code&gt; method through a sandbox (typically looks like 				&lt;code&gt;this.stub(...)&lt;/code&gt;), you can now stub any kind of property, not just functions. This is useful if you want to override some value inside a single test and have it automatically restored afterwards.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_4&quot;&gt;Mocks&lt;/h2&gt;
&lt;p&gt;
Mocks have received quite an overhaul. Previously, Sinon.JS would only consider mock expectations in the strict order they were defined. This has never been the exact intention, and was considered a bug. This fact was confirmed by people reporting to me that this behavior was unexpected. In any case, you can now define mock expectations as you wish, and when the mock is called, Sinon will figure out which expectation to consume next.
&lt;/p&gt;

&lt;p&gt;
Additionally, mocks have significantly improved their error reporting. For instance, consider the following example from the docs:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test mock failure messages&amp;quot;: function () {
    var myAPI = { method: function () {} };

    var mock = sinon.mock(myAPI);
    mock.expects(&amp;quot;method&amp;quot;).withArgs(42).once().returns(true);
    mock.expects(&amp;quot;method&amp;quot;).twice().returns(2);

    myAPI.method();

    mock.verify();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
With Sinon.JS 1.0.2 and below, this test would fail with &amp;quot;method received no arguments, expected 42&amp;quot;. In 1.1.0, you'll get this:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;Expected method(42[, ...]) once (never called)
Expected method([...]) twice (called once)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
In other words, Sinon will print a full report of expected and received calls. This should entirely remove the need to whip out some logging statement or additional asserts to figure out why your tests are failing.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_5&quot;&gt;Assertions&lt;/h2&gt;
&lt;p&gt;
Related to the mock improvements are the new and improved failure messages from assertions. As you know, testing is all about getting as much valuable feedback as possible, and Sinon has stepped it up one notch.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test assertion failure messages&amp;quot;: function () {
    var myAPI = { method: function () {} };

    sinon.stub(myAPI, &amp;quot;method&amp;quot;).returns(true);

    myAPI.method();
    myAPI.method(42);
    myAPI.method(&amp;quot;Hey&amp;quot;, &amp;quot;There&amp;quot;, &amp;quot;Fella&amp;quot;);

    sinon.assert.calledOnce(myAPI.method);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Sinon.JS 1.0.2 and below will fail this test with &amp;quot;expected method to be called once but was called thrice&amp;quot;. In 1.1.0 you get:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;expected method to be called once but was called thrice
    method() =&amp;gt; true
    method(42) =&amp;gt; true
    method(Hey, There, Fella) =&amp;gt; true&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Sinon now also exposes the 				&lt;code&gt;sinon.format(object)&lt;/code&gt; method which you can override if you want more intelligent formatting of arguments. The default implementation simply coerces objects to strings, but you could do fancy stuff like quote strings and so on. Sinon 1.2.0 will ship with awesome formatting.
&lt;/p&gt;
	&lt;h2 id=&quot;toc231331_6&quot;&gt;The fake server&lt;/h2&gt;	&lt;h3 id=&quot;toc231331_6_1&quot;&gt;Auto responding - mockup development with Sinon.JS&lt;/h3&gt;
&lt;p&gt;
Some work has been done on the fake server to make it suitable for mockup development. By calling 				&lt;code&gt;server.autoRespond(10);&lt;/code&gt;, the server will automatically respond to requests after 10ms. This means you can drop in Sinon.JS and a server.js file on an HTML page to work with a fake server, defined in JavaScript.
&lt;/p&gt;
	&lt;h3 id=&quot;toc231331_6_2&quot;&gt;Response functions&lt;/h3&gt;
&lt;p&gt;
The 				&lt;code&gt;respondWith&lt;/code&gt; method accepts a wide variety of arguments, as it has done. What's new in 1.1.0 is that it will now accept three types of responses: a string, which defines the body of the response (old), an array: 				&lt;code&gt;[200, { &amp;quot;Headers&amp;quot;: &amp;quot;here&amp;quot; }, &amp;quot;Body&amp;quot;]&lt;/code&gt; (old) &lt;b&gt;and&lt;/b&gt; a function.
&lt;/p&gt;

&lt;p&gt;
When using a function to respond to the request, it will receive the 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; object. You can also specify URL and so on, but the function has the final word. The function is only called when method and URL (if any) match, and then it can decide to respond or not (by calling 				&lt;code&gt;respond&lt;/code&gt; on the 				&lt;code&gt;xhr&lt;/code&gt; object):
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;server.respondWith(&amp;quot;GET&amp;quot;, &amp;quot;/todo-items&amp;quot;, function (xhr) {
    xhr.respond(200, { &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot; }, '[]');
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Additionally, you can add capture groups to URL regular expressions, and the function will receive whatever is caught:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;server.respondWith(/\/todo-items\/(\d+)/, function (xhr, id) {
    xhr.respond(200, { &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot; }, '[{ &amp;quot;id&amp;quot;: ' + id + ' }]');
});&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc231331_7&quot;&gt;The website&lt;/h2&gt;
&lt;p&gt;
			
									&lt;a href=&quot;http://sinonjs.org&quot;&gt;The website&lt;/a&gt; also got a small facelift. I once again changed the docs, now they're back on one really long page. I'm kinda struggling to find the proper format for the documentation, so please don't hesitate to get in touch if you have problems understanding Sinon.JS, or you have ideas on how to improve the docs.
&lt;/p&gt;

&lt;p&gt;
Finally, thanks a lot to everyone who uses Sinon.JS, everyone who contributed patches, reported bugs and generally showed interest. Keep 'em coming.
&lt;/p&gt;

&lt;p&gt;
Now, 			
									&lt;a href=&quot;http://sinonjs.org&quot;&gt;get Sinon.JS 1.1.0&lt;/a&gt; and 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;let me know what you think&lt;/a&gt;!
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>04 Apr 2011 23:14:37 GMT</pubDate>
  <title>Want to learn TDD?</title>
  <link>http://www.cjohansen.no/en/javascript/want_to_learn_tdd</link>
  <guid>http://www.cjohansen.no/en/javascript/want_to_learn_tdd</guid>
  <comments>http://www.cjohansen.no/en/javascript/want_to_learn_tdd#comments</comments>
  <description>
    
&lt;p&gt;
Eager to learn how to test-drive your JavaScript? Come join me at 			
									&lt;a href=&quot;http://falsyvalues.com/&quot;&gt;Falsy values&lt;/a&gt; in Warsaw in May, where I will give a &lt;b&gt;full day TDD workshop&lt;/b&gt;.
&lt;/p&gt;

    
&lt;p&gt;
On May 18th through the 20th, a unique kind of conference is going down in Warsaw, Poland. Falsy Values is two days of workshops and one day of &amp;quot;regular&amp;quot; talks. I'll be giving my TDD workshop on the 19th, and if you stay to the 20th you can attend talks by awesome speakers such as Douglas Crockford, Juriy &amp;quot;kangax&amp;quot; Zaytsev and others.
&lt;/p&gt;

&lt;p&gt;
My workshop will focus around the topics in 			
									&lt;a href=&quot;http://tddjs.com&quot;&gt;my book&lt;/a&gt; in a very practical manner. I will be live-coding as we discuss aspects of the TDD workflow, and attendees will be doing practical labs to get hands-on experience. Some topics we will cover include:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;How to write good unit tests&lt;/li&gt;

&lt;li&gt;Tools to improve your workflow&lt;/li&gt;

&lt;li&gt;Code katas for learning and practicing TDD&lt;/li&gt;

&lt;li&gt;TDD and browser-based applications&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
The price? A measly € 139.00. 			
									&lt;a href=&quot;http://falsyvalues.com/registration.html&quot;&gt;Order a seat right now&lt;/a&gt;, and I'll see you in Poland!
&lt;/p&gt;

&lt;p&gt;
To those of you in Norway who can't join me in Poland, there is also an upcoming course at 			
									&lt;a href=&quot;http://www.programutvikling.no/kurskalenderoversikt.aspx?mid_1=1352&amp;amp;mid=1535&amp;amp;id=968168&quot;&gt;Programutvikling AS&lt;/a&gt; (Oslo). If Oslo is too far away, get in touch for in-house training at your company.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>31 Oct 2010 00:11:19 GMT</pubDate>
  <title>Using Sinon.JS with QUnit</title>
  <link>http://www.cjohansen.no/en/javascript/using_sinon_js_with_qunit</link>
  <guid>http://www.cjohansen.no/en/javascript/using_sinon_js_with_qunit</guid>
  <comments>http://www.cjohansen.no/en/javascript/using_sinon_js_with_qunit#comments</comments>
  <description>
    
&lt;p&gt;
Since my talk at Front-Trends in Poland last week I've gotten a few requests for examples of using 			
									&lt;a href=&quot;http://cjohansen.no/sinon&quot;&gt;Sinon.JS&lt;/a&gt; with 			
									&lt;a href=&quot;http://docs.jquery.com/QUnit&quot;&gt;QUnit&lt;/a&gt;. Sinon.JS is completely test framework agnostic and should be very easy to use with any testing framework. This post introduces a mini-plugin, 			
									&lt;a href=&quot;http://cjohansen.no/sinon/releases/sinon-qunit-0.8.0.js&quot;&gt;sinon-qunit&lt;/a&gt; and shows a few examples of using Sinon.JS with QUnit.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc215435_1&quot;&gt;Spies, stubs and mocks&lt;/h2&gt;
&lt;p&gt;
Using one-off spies, stubs and mocks is straight-forward, and does not require anything extra. Set up a QUnit test case HTML file like so:
&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;!DOCTYPE html PUBLIC &amp;quot;-//W3C//DTD HTML 4.01//EN&amp;quot; &amp;quot;http://www.w3.org/TR/html4/strict.dtd&amp;quot;&amp;gt;
&amp;lt;html lang=&amp;quot;en&amp;quot;&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;QUnit/Sinon.JS&amp;lt;/title&amp;gt;
    &amp;lt;link rel=&amp;quot;stylesheet&amp;quot; href=&amp;quot;qunit.css&amp;quot; type=&amp;quot;text/css&amp;quot; media=&amp;quot;screen&amp;quot; /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1 id=&amp;quot;qunit-header&amp;quot;&amp;gt;QUnit/Sinon.JS Test&amp;lt;/h1&amp;gt;
    &amp;lt;h2 id=&amp;quot;qunit-banner&amp;quot;&amp;gt;&amp;lt;/h2&amp;gt;
    &amp;lt;h2 id=&amp;quot;qunit-userAgent&amp;quot;&amp;gt;&amp;lt;/h2&amp;gt;
    &amp;lt;ol id=&amp;quot;qunit-tests&amp;quot;&amp;gt;&amp;lt;/ol&amp;gt;
    &amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;jquery.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;qunit.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;sinon-0.8.0.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;sinon-ie-0.8.0.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;!-- Source and test files go here --&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This is just a vanilla QUnit setup, with two additional files - Sinon.JS and the IE fix. With this in place you can use stubs and spies like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;test(&amp;quot;Using spies&amp;quot;, function () {
    var spy = sinon.spy();
    spy();

    ok(spy.called);
    ok(spy.calledOnce);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As long as you are not messing with the global environment, this works as expected.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215435_2&quot;&gt;Faking global methods&lt;/h2&gt;
&lt;p&gt;
If you want to spy on, stub or mock global methods, like 				&lt;code&gt;jQuery.ajax&lt;/code&gt;, the above approach will give you trouble because the fakes are not restored after the test has run. The 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon&quot;&gt;higher-level helpers in Sinon.JS&lt;/a&gt; can easily be used as previously explained with QUnit through the help of 			
									&lt;a href=&quot;http://cjohansen.no/sinon/releases/sinon-qunit-0.8.0.js&quot;&gt;sinon-qunit&lt;/a&gt;. Add the following line to the HTML file:
&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;sinon-qunit-0.8.0.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then you can use 				&lt;code&gt;spy&lt;/code&gt;, 				&lt;code&gt;stub&lt;/code&gt; and 				&lt;code&gt;mock&lt;/code&gt; as properties of 				&lt;code&gt;this&lt;/code&gt; inside the test:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;test(&amp;quot;Stubbing global environments&amp;quot;: function () {
    this.stub(jQuery, &amp;quot;ajax&amp;quot;);
    jQuery.ajax(&amp;quot;/url&amp;quot;, {});

    ok(jQuery.ajax.called);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
When the test is done running, the 				&lt;code&gt;jQuery.ajax&lt;/code&gt; method is restored to the original one.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215435_3&quot;&gt;Timers&lt;/h2&gt;
&lt;p&gt;
The 				&lt;code&gt;clock&lt;/code&gt; property works as 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/faking_timers_and_dates_with_sinon&quot;&gt;previously explained&lt;/a&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;test(&amp;quot;Some timing stuff&amp;quot;, function () {
    var spy = this.spy();
    setTimeout(spy, 150);

    this.clock.tick(149);
    ok(!spy.called);

    this.clock.tick(1);
    ok(spy.called);
});&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc215435_4&quot;&gt;XMLHttpRequest and the fake server&lt;/h2&gt;
&lt;p&gt;
The final piece of the puzzle is the fake server. The default configuration for 				&lt;code&gt;sinon-qunit&lt;/code&gt; is slightly more conservative than the default one. It does not automatically stub 				&lt;code&gt;XMLHttpRequest&lt;/code&gt;. However, you can easily use it. All you have to do is to call 				&lt;code&gt;this.sandbox.useFakeServer&lt;/code&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;test(&amp;quot;should make request&amp;quot;, function () {
    var server = this.sandbox.useFakeServer();
    var dataSource = new XHRDataSource();
    dataSource.get();

    equal(1, server.requests.length);
});&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc215435_5&quot;&gt;More examples&lt;/h2&gt;
&lt;p&gt;
If you're keen on seeing more examples, I've update 			
									&lt;a href=&quot;http://github.com/cjohansen/fronttrends-2010&quot;&gt;the repository for the code from my Front-Trends 2010 talk&lt;/a&gt;. It now includes a directory with all the tests updated for QUnit, so you can compare them to the original JsTestDriver tests.
&lt;/p&gt;

&lt;p&gt;
The test case can be 			
									&lt;a href=&quot;http://cjohansen.no/sinon/qunit-example/&quot;&gt;viewed live here&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
The live search functional test shows how you can use Sinon.JS to stub network requests:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;test(&amp;quot;should display suggestions as user types&amp;quot;, function () {
    var server = this.sandbox.useFakeServer();

    server.respondWith(
        &amp;quot;GET&amp;quot;, &amp;quot;/search?q=Robo&amp;quot;,
        [200, { &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot; },
         '[&amp;quot;Robocop&amp;quot;, &amp;quot;Robocop 2&amp;quot;, &amp;quot;Robocop 3&amp;quot;]']
    );

    server.respondWith(
        &amp;quot;GET&amp;quot;, &amp;quot;/search?q=Roboc&amp;quot;,
        [200, { &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot; },
         '[&amp;quot;Robocop&amp;quot;, &amp;quot;Robocop 2&amp;quot;, &amp;quot;Robocop 3&amp;quot;]']
    );

    var form = jQuery(&amp;quot;#qunit-fixture&amp;quot;);
    form.liveSearch();
    var input = form.find(&amp;quot;input[type=text]&amp;quot;);

    input.val(&amp;quot;R&amp;quot;);
    input.trigger(&amp;quot;keyup&amp;quot;);
    this.clock.tick(89);

    input.val(&amp;quot;Ro&amp;quot;);
    input.trigger(&amp;quot;keyup&amp;quot;);
    this.clock.tick(98);

    input.val(&amp;quot;Rob&amp;quot;);
    input.trigger(&amp;quot;keyup&amp;quot;);
    this.clock.tick(69);

    input.val(&amp;quot;Robo&amp;quot;);
    input.trigger(&amp;quot;keyup&amp;quot;);
    this.clock.tick(109);

    var results = form.find(&amp;quot;ol.live-search-results li&amp;quot;);
    equal(0, results.length);

    input.val(&amp;quot;Roboc&amp;quot;);
    input.trigger(&amp;quot;keyup&amp;quot;);
    this.clock.tick(150);

    server.respond();

    results = form.find(&amp;quot;ol.live-search-results li&amp;quot;);
    equal(3, results.length);
    equal(&amp;quot;Robocop&amp;quot;, results.get(0).innerHTML);
    equal(&amp;quot;Robocop 2&amp;quot;, results.get(1).innerHTML);
    equal(&amp;quot;Robocop 3&amp;quot;, results.get(2).innerHTML);
});&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc215435_6&quot;&gt;Known issues&lt;/h2&gt;
&lt;p&gt;
Everything in Sinon.JS works as expected with the QUnit plugin, even the assertions. However, when using the Sinon.JS assertions, QUnit does not get the assertion counter right, as you can see on the above live search example.
&lt;/p&gt;

&lt;p&gt;
Let me know what you think, either here, or 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;find me on Twitter (@cjno)&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>25 Oct 2010 23:43:38 GMT</pubDate>
  <title>FrontTrends 2010</title>
  <link>http://www.cjohansen.no/en/javascript/fronttrends_2010</link>
  <guid>http://www.cjohansen.no/en/javascript/fronttrends_2010</guid>
  <comments>http://www.cjohansen.no/en/javascript/fronttrends_2010#comments</comments>
  <description>
    
&lt;p&gt;
Last week I gave a talk at FrontTrends 2010. Here's the code from my talk, and a brief summary of it.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc215323_1&quot;&gt;Test-first JavaScript&lt;/h2&gt;
&lt;p&gt;
My talk was entitled 			
									&lt;a href=&quot;http://front-trends.com/speakers/christian-johansen&quot;&gt;Test-first JavaScript&lt;/a&gt; and was a hands-on tutorial on TDD with JavaScript. I spent a few minutes presenting the central idea of TDD - &lt;i&gt;Clean code that works, now&lt;/i&gt; (Kent Beck), and the four steps:
&lt;/p&gt;

&lt;ol&gt;

&lt;li&gt;Write a test&lt;/li&gt;

&lt;li&gt;Watch it fail&lt;/li&gt;

&lt;li&gt;Pass the test&lt;/li&gt;

&lt;li&gt;Remove duplication&lt;/li&gt;

&lt;/ol&gt;

&lt;p&gt;
Then I fired up Emacs and spent the better part of an hour live coding, TDD-ing the start of a live search jQuery plugin. The sample code is 			
									&lt;a href=&quot;http://github.com/cjohansen/fronttrends-2010&quot;&gt;available on GitHub&lt;/a&gt;, but heed this warning: About half of this code was written &amp;quot;before a live audience&amp;quot;, and the rest was prepared in order to show the final demo (which I failed to do anyway).
&lt;/p&gt;

&lt;p&gt;
The code is only the start of a plugin, and isn't actually functional for anything else than displaying suggestions. The most important part of the presentation was not the code itself, but rather the process of writing it - guided by tests. So take the code for what it is. Instructions for running the hackety Node.js server and testing the whole thing is available on GitHub.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215323_2&quot;&gt;How did it go?&lt;/h2&gt;
&lt;p&gt;
There was a surprising amount of people on my talk, and I want to thank you all for showing up! Only a few have 			
									&lt;a href=&quot;http://speakerrate.com/talks/4910-test-first-javascript&quot;&gt;voted for the talk&lt;/a&gt; so far, but judging from what they had to say, people had a good time.
&lt;/p&gt;

&lt;p&gt;
I actually messed up my final demo, which is to be expected when one sets out for a full hour of live coding, but I don't think it really mattered. The demo was mostly for a small wow-effect as the topic is a bit dry on its own. It seems people got the message despite some technical issues. After the presentation it hit me that my error was to omit jquery.js when concatenating the scripts towards the end.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215323_3&quot;&gt;Questions, questions, questions!&lt;/h2&gt;
&lt;p&gt;
There were lots of questions during my talk, and I really appreciated them. People seemed engaged and had lots of good comments. I'd love to discuss testing and JavaScript anytime, so hit me 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;on Twitter&lt;/a&gt;, here, or on christian@cjohansen.no if you're interested in having me talk more about this, discussing something or whatever!
&lt;/p&gt;

&lt;p&gt;
Marcin Kasperski has posted a 			
									&lt;a href=&quot;http://notatnik.mekk.waw.pl/archives/242-Front-Trends_2010_-_czesc_2.html&quot;&gt;very nice summary of FrontTrends 2010&lt;/a&gt;, including a very flattering review of my talk, check it out! (It's in Polish, but Google translate does the job). Thanks Marcin!
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>16 Oct 2010 00:37:50 GMT</pubDate>
  <title>JavaScript continuous integration with Hudson and JsTestDriver</title>
  <link>http://www.cjohansen.no/en/javascript/javascript_continuous_integration_with_hudson_and_jstestdriver</link>
  <guid>http://www.cjohansen.no/en/javascript/javascript_continuous_integration_with_hudson_and_jstestdriver</guid>
  <comments>http://www.cjohansen.no/en/javascript/javascript_continuous_integration_with_hudson_and_jstestdriver#comments</comments>
  <description>
    
&lt;p&gt;
JsTestDriver's JUnit compatible XML output makes it dead simple to set up JavaScript continuous integration. This post will help you get started with Hudson.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc215055_1&quot;&gt;Installing Hudson&lt;/h2&gt;
&lt;p&gt;
Setting up continuous integration with Hudson is pretty simple - especially if you're on a Debian based Linux. 			
									&lt;a href=&quot;http://hudson-ci.org&quot;&gt;hudson-ci.org&lt;/a&gt; has 			
									&lt;a href=&quot;http://hudson-ci.org/debian/&quot;&gt;a nice and simple recipe for installing the Hudson .deb&lt;/a&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;wget -O /tmp/key http://hudson-ci.org/debian/hudson-ci.org.key
sudo apt-key add /tmp/key
wget -O /tmp/hudson.deb http://hudson-ci.org/latest/debian/hudson.deb
sudo dpkg --install /tmp/hudson.deb&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The .deb will not automatically install dependencies, so depending on your system, the installation might fail in the face of missing dependencies. If that's the case, simply copy the name of the missing packages, and run 				&lt;code&gt;`apt-get install pacakge1 package2`&lt;/code&gt;. In my case I was missing the daemon package, so I also had to run
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;sudo apt-get install daemon&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
And then the Hudson install finished automatically.
&lt;/p&gt;

&lt;p&gt;
This is really all you need, and Hudson should now be running on 			
									&lt;a href=&quot;http://localhost:8080&quot;&gt;http://localhost:8080&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215055_2&quot;&gt;Installing required plugins&lt;/h2&gt;
&lt;p&gt;
In order to run the tests with Hudson we need to install a single plugin. Depending on your version control software of choice, you might also want to get a plugin to support it. I use Git, so I'll show you how to run JsTestDriver jobs from a Git repository. 
&lt;/p&gt;

&lt;p&gt;
From the frontpage, click on &amp;quot;Manage Hudson&amp;quot;, then &amp;quot;Manage Plugins&amp;quot;. Hit the 			
									&lt;a href=&quot;http://localhost:8080/pluginManager/available&quot;&gt;&amp;quot;Available&amp;quot; pane&lt;/a&gt;. Tick the checkbox next to &amp;quot;Git Plugin&amp;quot; (if you use Git), and the box next to &amp;quot;xUnit Plugin&amp;quot;. All the way in the lower right corner you will find an &amp;quot;Install&amp;quot; button. Click it. When Hudson completes the installation, follow through and click the &amp;quot;Restart when no jobs are running&amp;quot; button.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215055_3&quot;&gt;Configuring a JsTestDriver project with Hudson&lt;/h2&gt;
&lt;p&gt;
When Hudson is back up, click the 			
									&lt;a href=&quot;http://localhost:8080/newJob&quot;&gt;create new job&lt;/a&gt; displayed on the restart page. Give the job a name, such as &amp;quot;My Tested JS Project&amp;quot;. Choose to &amp;quot;Build a free-style software project&amp;quot; and then hit &amp;quot;OK&amp;quot;.
&lt;/p&gt;
	&lt;h3 id=&quot;toc215055_3_1&quot;&gt;Optional: Configure the Git repository&lt;/h3&gt;
&lt;p&gt;
If you use Git, choose the Git option under &amp;quot;Source Code Management&amp;quot;. New fields will appear. The easiest way to test is to just create a temporary local repository:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;➜  ~  mkdir -p /tmp/git/myproject.git
➜  ~  git init --bare /tmp/git/myproject.git&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Tell Hudson the location of the Git repository by entering &amp;quot;file:///tmp/git/myproject.git&amp;quot; into the &amp;quot;URL of repository&amp;quot; field. The rest are optional, if you don't know what to do with them, just leave them as is.
&lt;/p&gt;

&lt;p&gt;
Also, importantly, Hudson will fail unless you configure Git for the hudson user. This is simple to do:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;➜  ~  sudo su hudson
➜  ~  git config --global user.name &amp;quot;Hudson&amp;quot;
➜  ~  git config --global user.email &amp;quot;hudson@localhost&amp;quot;&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc215055_4&quot;&gt;Build triggers&lt;/h2&gt;
&lt;p&gt;
Next we need to set up a build trigger. You will likely have your own opinion on how to do this, but for the purpose of this guide, we will set Hudson to poll the SCM. When you tick the box next to &amp;quot;Poll the SCM&amp;quot;, Hudson prompts for a schedule. It expects a cron-like pattern. For instance, to poll once every hour on the hour, enter 				&lt;code&gt;0 * * * *&lt;/code&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215055_5&quot;&gt;Build step&lt;/h2&gt;
&lt;p&gt;
We only need one build step in this project, namely the JsTestDriver task. Hit &amp;quot;Add build step&amp;quot; and select &amp;quot;Execute shell&amp;quot;. Then enter the following command:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;java -jar test/JsTestDriver-1.2.2.jar \
  --config jsTestDriver.conf \
  --server http://localhost:4223 
  --tests all --testOutput . --reset&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Note that this assumes that you will make sure the server runs separately, and that it has browsers attached to it. I've found this to work the best. It also assumes that you bundle JsTestDriver-1.2.2.jar inside the test directory in your project. If this is not the case, adjust accordingly. Same goes for the path to the configuration file.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215055_6&quot;&gt;Post-build Actions&lt;/h2&gt;
&lt;p&gt;
Under &amp;quot;Post-build Actions&amp;quot;, select &amp;quot;Publish JUnit test result report&amp;quot;, and enter TEST-*.xml as the pattern.
&lt;/p&gt;

&lt;p&gt;
Finally, you can set up Email notification such that team members get an email when the build fails if you prefer. To do so, select &amp;quot;E-mail Notification&amp;quot; and list the desired email addresses separated by a space.
&lt;/p&gt;

&lt;p&gt;
Finally, hit &amp;quot;Save&amp;quot; and your project should be created.
&lt;/p&gt;
	&lt;h2 id=&quot;toc215055_7&quot;&gt;Start the JsTestDriver server&lt;/h2&gt;
&lt;p&gt;
From the same machine, start JsTestDriver on port 4223:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;java -jar test/JsTestDriver-1.2.2.jar --port 4223&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Capture a few browsers to 			
									&lt;a href=&quot;http://localhost:4223&quot;&gt;http://localhost:4223&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
If you're using Git as I am, push to the local repository:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;git remote add local file:///tmp/git/myproject.git
git push local master&lt;/code&gt;&lt;/pre&gt;
	&lt;h2 id=&quot;toc215055_8&quot;&gt;Build it&lt;/h2&gt;
&lt;p&gt;
The final step is to try a build. You can either grab a coffee and wait for Hudson to build on the schedule you configured, or you can issue a build manually. In the left column on your project page, there's a link called &amp;quot;Build now&amp;quot;. Click it. Now. Hudson will start processing your build, and hopefully if all goes well, it will stop with a blue ball indicating success.
&lt;/p&gt;

&lt;p&gt;
If you're more comfortable with red/green as fail/success indicators, there's a plugin called &amp;quot;Green balls&amp;quot; which you can install from the 			
									&lt;a href=&quot;http://localhost:8080/pluginManager/&quot;&gt;plugin manager&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
When you're all done, it should look something like this: 
&lt;/p&gt;

&lt;div class=&quot;object-center&quot;&gt;&lt;div class=&quot;image&quot;&gt;
  	
	
	
	
	
	
				&lt;img src=&quot;/var/cj_no/storage/images/media/images/hudson/215063-1-nor-NO/hudson_article.png&quot; width=&quot;469&quot; height=&quot;400&quot; alt=&quot;&quot; /&gt;	
	&lt;/div&gt;
&lt;/div&gt;
  </description>
</item>
            <item>
  <pubDate>23 Sep 2010 00:38:19 GMT</pubDate>
  <title>Patching JsTestDriver</title>
  <link>http://www.cjohansen.no/en/javascript/patching_jstestdriver</link>
  <guid>http://www.cjohansen.no/en/javascript/patching_jstestdriver</guid>
  <comments>http://www.cjohansen.no/en/javascript/patching_jstestdriver#comments</comments>
  <description>
    
&lt;p&gt;
I hacked a little on JsTestDriver today, fixing a few bugs in some assertions, and possibly more interestingly - improved assertion error messages for certain types of objects.
&lt;/p&gt;

    
&lt;p&gt;
&lt;b&gt;tl;dr&lt;/b&gt;			
									&lt;a href=&quot;/jstestdriver/asserts-fix-76-106-120-129-142.diff&quot;&gt;download the patch&lt;/a&gt; (to apply to local build of JsTestDriver), or 			
									&lt;a href=&quot;/jstestdriver/Asserts.js&quot;&gt;a readily patched Asserts.js file&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc214637_1&quot;&gt;Bug fixes&lt;/h2&gt;
&lt;p&gt;
I fixed the following bugs in the patch:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/issues/detail?id=76&quot;&gt;#76 Unprotected undefined in Asserts.js&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/issues/detail?id=106&quot;&gt;#106 assertEquals with objects should check with === first&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/issues/detail?id=120&quot;&gt;#120 assertInstanceOf doesn't fail for undefined variables&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/issues/detail?id=129&quot;&gt;#129 assertEquals does not work for DOM elements&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/issues/detail?id=142&quot;&gt;#142 assertEquals(null, new Date) passes&lt;/a&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
What this means is that 				&lt;code&gt;assertEquals&lt;/code&gt; is now safer to use, and you can now use it with DOM nodes, which was impossible before. I'm a little worried that the method will still produce false positives in some cases where the objects compared have no enumerable properties, but I'll look further into this.
&lt;/p&gt;
	&lt;h2 id=&quot;toc214637_2&quot;&gt;Error messages&lt;/h2&gt;
&lt;p&gt;
So to the &amp;quot;itch scratching&amp;quot; - I've been slightly annoyed for a while about how JsTestDriver reports certain types of objects when assertions fail. For instance, if you were to do the following:
&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;quot;test compare DOM nodes&amp;quot;: function () {
    var span = document.createElement(&amp;quot;span&amp;quot;);
    span.id = &amp;quot;hey&amp;quot;;
    span.className = &amp;quot;note text&amp;quot;;
    var ol = document.createElement(&amp;quot;ol&amp;quot;);
    ol.class = &amp;quot;items&amp;quot;;

    assertSame(span, ol);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
JsTestDriver would produce a message along the lines of &amp;quot;expected {} but was {}&amp;quot; - or even worse - &amp;quot;Converting circular structure to JSON&amp;quot; - which is not really helpful at all. Additionally, as I explained above, had you used 				&lt;code&gt;assertEquals&lt;/code&gt; in place of 				&lt;code&gt;assertSame&lt;/code&gt; you'd run the risk of the test actually passing. Oops!
&lt;/p&gt;

&lt;p&gt;
With my patch the above test will rather fail with the following message: 'expected &amp;lt;span id=&amp;quot;hey&amp;quot; class=&amp;quot;note text&amp;quot;&amp;gt;...&amp;lt;/span&amp;gt; but was &amp;lt;ol class=&amp;quot;items&amp;quot;&amp;gt;...&amp;lt;/ol&amp;gt;', which is a bit more verbose, but also vastly more helpful.
&lt;/p&gt;
	&lt;h3 id=&quot;toc214637_2_1&quot;&gt;Functions&lt;/h3&gt;
&lt;p&gt;
While I was at it I also made a minor improvement to the string representation of functions. If you're comparing functions, and the function has a name, rather than &amp;quot;expeced [function] but was [function]&amp;quot; you will see &amp;quot;expected function aFunc() but was function getSomething&amp;quot;, which, again, helps locate failures faster.
&lt;/p&gt;

&lt;p&gt;
That's really all there is to it. If you build JsTestDriver from source, you can apply the 			
									&lt;a href=&quot;/jstestdriver/asserts-fix-76-106-120-129-142.diff&quot;&gt;following patch&lt;/a&gt; to trunk. If you don't you can 			
									&lt;a href=&quot;/jstestdriver/Asserts.js&quot;&gt;download a readily patched Asserts.js file&lt;/a&gt; and simply add it as the first file to be loaded in 				&lt;code&gt;jsTestDriver.conf&lt;/code&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>02 Sep 2010 22:37:05 GMT</pubDate>
  <title>Live coding help from Git and Emacs</title>
  <link>http://www.cjohansen.no/en/emacs/live_coding_help_from_git_and_emacs</link>
  <guid>http://www.cjohansen.no/en/emacs/live_coding_help_from_git_and_emacs</guid>
  <comments>http://www.cjohansen.no/en/emacs/live_coding_help_from_git_and_emacs#comments</comments>
  <description>
    
&lt;p&gt;
A small git script and two lisp functions can go a long way in helping you &amp;quot;live code&amp;quot; in a prepared and controlled matter at conferences.
&lt;/p&gt;

    
&lt;p&gt;
So, next week I'm speaking at 			
									&lt;a href=&quot;http://jz10.java.no/&quot;&gt;JavaZone&lt;/a&gt;, and I'm planning on a couple of minor coding sessions. Just in case the demo monster visits and I fuck up entirely, I've got some insurance.
&lt;/p&gt;

&lt;p&gt;
With a little help from my good friends Git and Emacs (oh and also my human friend 			
									&lt;a href=&quot;http://ditrw.com&quot;&gt;August&lt;/a&gt;) I've set it up so I can run through recorded steps of the coding exercise if all else fails.
&lt;/p&gt;
	&lt;h2 id=&quot;toc214381_1&quot;&gt;Extending Git with Ruby&lt;/h2&gt;
&lt;p&gt;
August wrote a small Git script a while back, 			
									&lt;a href=&quot;http://github.com/augustl/binbin/blob/master/git-walk&quot;&gt;git-walk&lt;/a&gt;. 				&lt;code&gt;git-walk next&lt;/code&gt; and 				&lt;code&gt;git-walk prev&lt;/code&gt; moves your repository one commit forward or backward, respectively. This means you can prepare a coding session - however detailed you want it - and record each step in a git commit.
&lt;/p&gt;
	&lt;h2 id=&quot;toc214381_2&quot;&gt;Shelling out with Lisp&lt;/h2&gt;
&lt;p&gt;
And then for the cool part: I wrote three very simple Lisp functions that I can issue with a key binding in Emacs. I recon I'll use these when visiting relevant buffers, so for good measure I added in a call to 				&lt;code&gt;revert-buffer&lt;/code&gt;, which causes the buffer to reload from the file. 				&lt;code&gt;revert-buffer&lt;/code&gt; normally asks for confirmation, but you can suppress that by passing a non-nil argument as the second argument. The 			
									&lt;a href=&quot;http://gist.github.com/562897&quot;&gt;final functions&lt;/a&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;(defun git-walk (direction)
  (interactive)
  (shell-command (concat &amp;quot;git walk &amp;quot; direction))
  (revert-buffer nil t))

(defun git-walk-next ()
  (interactive)
  (git-walk &amp;quot;next&amp;quot;))

(defun git-walk-prev ()
  (interactive)
  (git-walk &amp;quot;prev&amp;quot;))

;; Key-bindings
(global-set-key (kbd &amp;quot;C-c &amp;lt;right&amp;gt;&amp;quot;) 'git-walk-next)
(global-set-key (kbd &amp;quot;C-c &amp;lt;left&amp;gt;&amp;quot;) 'git-walk-prev)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As you can see I bound these to 				&lt;code&gt;C-c [arrow left/right]&lt;/code&gt;. Very handy backup.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>10 Aug 2010 21:58:21 GMT</pubDate>
  <title>Sinon.JS 0.6.0 - Fake XMLHttpRequest and improved test framework integration</title>
  <link>http://www.cjohansen.no/en/javascript/sinon_js_0_6_0_fake_xmlhttprequest_and_improved_test_framework_integration</link>
  <guid>http://www.cjohansen.no/en/javascript/sinon_js_0_6_0_fake_xmlhttprequest_and_improved_test_framework_integration</guid>
  <comments>http://www.cjohansen.no/en/javascript/sinon_js_0_6_0_fake_xmlhttprequest_and_improved_test_framework_integration#comments</comments>
  <description>
    
&lt;p&gt;
Sinon.JS 0.6.0 is out and it features a new 				&lt;code&gt;FakeXMLHttpRequest&lt;/code&gt; object and a high-level interface for testing xhr-dependent code along with improvements to 				&lt;code&gt;sinon.sandbox&lt;/code&gt; and 				&lt;code&gt;sinon.test&lt;/code&gt;.
&lt;/p&gt;

    
&lt;p&gt;
Warning: Slightly long, but thorough post. Short version is in 			
									&lt;a href=&quot;http://cjohansen.no/sinon/&quot;&gt;the currently basic API docs&lt;/a&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_1&quot;&gt;Testing &amp;quot;Ajax&amp;quot; Code&lt;/h2&gt;
&lt;p&gt;
Sinon.JS 0.6.0 sets out to provide an easy way to test code that makes server requests using the 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; object (or the 				&lt;code&gt;XMLHTTP&lt;/code&gt; ActiveXObject). The problem with testing such code is that you need a server replying to the requests, and you need tests to execute asynchronously in order to succeed. This means complicated test setup and possibly long-running tests, perhaps even timeouts if tests are run too fast.
&lt;/p&gt;

&lt;p&gt;
If you're using some kind library - and chances are you are - you can get around all this by using 				&lt;code&gt;sinon.stub&lt;/code&gt; or 				&lt;code&gt;sinon.mock&lt;/code&gt; to stub/mock e.g. 				&lt;code&gt;jQuery.ajax&lt;/code&gt;. This will work, but sometimes it's nice to be able to write mini-integration tests that runs both the request and the success callback in one go. Enter 				&lt;code&gt;sinon.useFakeXMLHttpRequest&lt;/code&gt;.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_2&quot;&gt;Faking XHR with Sinon.JS&lt;/h2&gt;
&lt;p&gt;
Sinon.JS 0.6.0 introduces 				&lt;code&gt;sinon.FakeXMLHttpRequest&lt;/code&gt;, a constructor that creates, well, fake 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; objects. They behave pretty much like native browser implementations, but they do not make actual requests. To use it, you call 				&lt;code&gt;sinon.useFakeXMLHttpRequest();&lt;/code&gt;, which returns an object with a 				&lt;code&gt;restore()&lt;/code&gt; method, much like other Sinon.JS fakes. When calling this function, Sinon.JS will replace the native 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; constructor (only if it exists) and/or the 				&lt;code&gt;ActiveXObject&lt;/code&gt; constructor (only if it exists) with the fake implementation. This means that you don't have to change your production code to test it using Sinon.JS. Note that only existing constructors are replaced, so for instance IE6 won't suddenly gain a &amp;quot;native&amp;quot; 				&lt;code&gt;XMLHttpRequest&lt;/code&gt;. Additionally, the 				&lt;code&gt;ActiveXObject&lt;/code&gt; constructor will continue to work as expected for progIds which are not related to 				&lt;code&gt;XMLHTTP&lt;/code&gt;.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_2_1&quot;&gt;Behavior verification on XHR objects&lt;/h3&gt;
&lt;p&gt;
The low-level way to use the fake xhr objects is to register a listener to receive all created xhr objects. The following test does so in order to perform behavior verification on them.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;// JsTestDriver test case, works with any testing framework
TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  setUp: function () {
    this.fakeXhr = sinon.useFakeXMLHttpRequest();
    var requests = this.requests = [];

    this.fakeXhr.onCreate = function (xhr) {
      requests.push(xhr);
    };
  },

  tearDown: function () {
    this.fakeXhr.restore();
  },

  &amp;quot;test something ajax-y&amp;quot;: function () {
    jQuery.ajax({ url: &amp;quot;/my/page&amp;quot; });

    assertEquals(&amp;quot;/my/page&amp;quot;, this.requests[0].url);
  }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As I mentioned, this is &lt;i&gt;the low-level way&lt;/i&gt; of testing the xhr objects. As you would expect, it requires a bit of setup. The test case simply collects any object created by way of 				&lt;code&gt;XMLHttpRequest&lt;/code&gt;/				&lt;code&gt;ActiveXObject&lt;/code&gt; (for 				&lt;code&gt;XMLHTTP&lt;/code&gt; progIds). The fake objects have a few properties that you can use for behavior verification:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;				&lt;code&gt;xhr.method&lt;/code&gt; The HTTP method&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;xhr.url&lt;/code&gt; The URL&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;xhr.async&lt;/code&gt; Boolean, usually 				&lt;code&gt;true&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;xhr.username&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;xhr.password&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;xhr.requestHeaders&lt;/code&gt; Object, e.g. 				&lt;code&gt;{ &amp;quot;Content-Type&amp;quot;: &amp;quot;text/html&amp;quot; }&lt;/code&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
In addition to these properties, you can call some methods on it to simulate a response coming through:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;				&lt;code&gt;c.status = 200;&lt;/code&gt; Assign status code.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;xhr.setResponseHeaders({});&lt;/code&gt; Sets all the response headers, and&lt;br /&gt; triggers 				&lt;code&gt;onreadystatechange&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;
				&lt;code&gt;xhr.setResponseBody(text);&lt;/code&gt; Sets the response body, and triggers
&lt;/p&gt;

&lt;p&gt;
				&lt;code&gt;onreadystatechange&lt;/code&gt;. Also, per the 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; spec, the
&lt;/p&gt;

&lt;p&gt;

				&lt;code&gt;responseXML&lt;/code&gt; property is populated with parsed XML if response headers&lt;br /&gt; indicates so.
&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;respond(status, headers, body);&lt;/code&gt; Performs all the above steps, and&lt;br /&gt; also sets the 				&lt;code&gt;responseText&lt;/code&gt; property according to 				&lt;code&gt;status&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Using these, you could write the above test like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  setUp: function () {
    this.fakeXhr = sinon.useFakeXMLHttpRequest();
    var requests = this.requests = [];

    this.fakeXhr.onCreate = function (xhr) {
      requests.push(xhr);
    };
  },

  tearDown: function () {
    this.fakeXhr.restore();
  },

  &amp;quot;test something ajax-y&amp;quot;: function () {
    var spy = sinon.spy();
    jQuery.ajax({ url: &amp;quot;/my/page&amp;quot;, success: spy });
    this.requests[0].respond(200, {}, &amp;quot;OK&amp;quot;);

    assert(spy.called);
  }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
In other words, using 				&lt;code&gt;respond()&lt;/code&gt; will cause the xhr object to act exactly as if it had gotten a response from the server.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_3&quot;&gt;A higher-level XHR testing abstraction&lt;/h2&gt;
&lt;p&gt;
I've tried to build Sinon.JS to be decoupled, layering increasingly higher-level concepts on top of solid low-level tools, like the one I just showed you. 				&lt;code&gt;FakeXMLHttpRequest&lt;/code&gt; is no exception. You can use the 				&lt;code&gt;sinon.fakeServer&lt;/code&gt; object to build a mock server for your tests that handles the requests for you. Take a look at our contrived example again:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  setUp: function () {
    this.server = sinon.fakeServer.create();
    this.server.respondWith([200, {}, &amp;quot;OK&amp;quot;]);
  },

  tearDown: function () {
    this.server.restore();
  },

  &amp;quot;test something ajax-y&amp;quot;: function () {
    var spy = sinon.spy();
    jQuery.ajax({ url: &amp;quot;/my/page&amp;quot;, success: spy });
    this.server.respond();

    assert(spy.called);
  }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The server requires less setup because it calls 				&lt;code&gt;sinon.useFakeXMLHttpRequest&lt;/code&gt; and handles the requests for you. Additionally, it provides a high-level API to set the server up to respond to requests. The 				&lt;code&gt;respondWith&lt;/code&gt; method adds capabilities to the server. It can be used in a number of ways:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith(&amp;quot;OK&amp;quot;);&lt;/code&gt; Always respond with a default status of&lt;br /&gt; 200, no headers and response text &amp;quot;OK&amp;quot;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith([200, { &amp;quot;Content-Length&amp;quot;: &amp;quot;2&amp;quot; }, &amp;quot;OK&amp;quot;]);&lt;/code&gt;&lt;br /&gt; Always respond with status 200, one header and response text &amp;quot;OK&amp;quot;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith(&amp;quot;/&amp;quot;, response);&lt;/code&gt; As above, 				&lt;code&gt;response&lt;/code&gt; is a&lt;br /&gt;
 string or an array. This response only goes out to requests for the &amp;quot;/&amp;quot;&lt;br /&gt; URL.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith(&amp;quot;GET&amp;quot;, &amp;quot;/&amp;quot;, response);&lt;/code&gt; As above, but only&lt;br /&gt; responds to GET requests to &amp;quot;/&amp;quot;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith(&amp;quot;GET&amp;quot;, &amp;quot;&amp;quot;, response);&lt;/code&gt; Responds to all GET&lt;br /&gt; requests (regardless of URL).&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;server.respondWith(&amp;quot;GET&amp;quot;, /\/post\/\d+/, response);&lt;/code&gt; Responds to all&lt;br /&gt; GET requests with a URL starting with &amp;quot;/post/&amp;quot; and followed by one or more numbers.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
You can call the 				&lt;code&gt;respondWith&lt;/code&gt; method as many times as you want to set up the server with capabilities. This means you can add one response within a single test, or set up a comprehensive mapping of your server in a separate file to share between tests.
&lt;/p&gt;

&lt;p&gt;
The upside of using the server is that it also handles synchronous requests. Whenever a synchronous request comes it, it is dealt with immediately. If an asynchronous requests comes by, it is queued, and you can tell the server to process all requests by calling 				&lt;code&gt;server.respond();&lt;/code&gt;. If none of the responses matches a given request, it receives a 				&lt;code&gt;[400, {}, &amp;quot;&amp;quot;]&lt;/code&gt; response.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_3_1&quot;&gt;&amp;quot;Faked&amp;quot; HTTP methods&lt;/h3&gt;
&lt;p&gt;
Frameworks like Ruby on Rails allow apps to use badly supported HTTP methods DELETE and PUT by piggy-backing a POST request with a 				&lt;code&gt;_method&lt;/code&gt; parameter in the body. Sinon.JS can do this too:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  setUp: function () {
    this.server = sinon.fakeServer.create();
    this.server.fakeHTTPMethods = true;
  },

  tearDown: function () {
    this.server.restore();
  },

  &amp;quot;test something ajax-y&amp;quot;: function () {
    var spy = sinon.spy();
    this.server.respondWith(&amp;quot;DELETE&amp;quot;, [200, {}, &amp;quot;OK&amp;quot;]);

    jQuery.ajax({
      url: &amp;quot;/my/page&amp;quot;,
      type: &amp;quot;post&amp;quot;,
      data: { method: &amp;quot;_delete&amp;quot; },
      success: spy
    });

    this.server.respond();

    assert(spy.called);
  }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As you can see, setting 				&lt;code&gt;server.fakeHTTPMethods = true&lt;/code&gt; tells Sinon.JS to look for 				&lt;code&gt;_method&lt;/code&gt; in the POST body. If your framework of choice does something similar, but not exactly like that you can simply override the 				&lt;code&gt;server.getHTTPMethod(request)&lt;/code&gt; method. The default one looks like this:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;getHTTPMethod: function getHTTPMethod(request) {
  if (this.fakeHTTPMethods &amp;amp;&amp;amp; /post/i.test(request.method)) {
    var match = request.requestBody.match(/_method=([^\b;]+)/);
    return !!match ? match[1] : request.method;
  }

  return request.method;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Override at will.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_3_2&quot;&gt;jQuery 1.3.x&lt;/h3&gt;
&lt;p&gt;
While testing Sinon.JS 0.6.0 on some code using jQuery 1.3.x, I discovered (after some cursing and table-slamming) that this version of jQuery does in fact not use 				&lt;code&gt;onreadystatechange&lt;/code&gt; at all. Instead, it uses 				&lt;code&gt;setInterval&lt;/code&gt; to poll the xhr object for completion. Because I'm guessing there's a lot of jQuery 1.3.x in the wild, I thought it might be nice to provide a solution. The solution is to use 				&lt;code&gt;sinon.fakeServerWithClock&lt;/code&gt; in place of 				&lt;code&gt;sinon.fakeServer&lt;/code&gt;. This object also uses the 				&lt;code&gt;clock&lt;/code&gt; object and fake 				&lt;code&gt;setInterval&lt;/code&gt; and friends as discussed previously. When you call 				&lt;code&gt;respond&lt;/code&gt; on this server, it also ticks the clock ahead long enough to fire all callbacks registered with 				&lt;code&gt;setTimeout&lt;/code&gt; and 				&lt;code&gt;setInterval&lt;/code&gt;.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_3_3&quot;&gt;The best of two worlds&lt;/h3&gt;
&lt;p&gt;
To provide you with the best of two worlds, the server object also exposes a 				&lt;code&gt;requests&lt;/code&gt; array which contains all the requests, in case you occasionally want to manage them manually.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_4&quot;&gt;Improved sandbox&lt;/h2&gt;
&lt;p&gt;
The 				&lt;code&gt;sinon.sandbox&lt;/code&gt; object discussed previously has been augmented to support the new XHR capabilities. Using it you can now collect all your stubs, spies and mocks along with faked timers and 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; in one convenient object. A single call to 				&lt;code&gt;sandbox.restore();&lt;/code&gt; will get everything back to normal. Restoring is especially important with JsTestDriver - failing to restore e.g. XHR will make it impossible for JsTestDriver to run any more tests (though it could've cached the object locally to be safe, but it doesn't).
&lt;/p&gt;

&lt;p&gt;
The contrived test once again, this time using the sandbox:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  setUp: function () {
    this.sandbox = sinon.sandbox.create();
    this.sandbox.useFakeServer();
    this.sandbox.useFakeTimers();
  },

  tearDown: function () {
    this.sandbox.restore();
  },

  &amp;quot;test something ajax-y&amp;quot;: function () {
    var spy = sinon.spy();

    jQuery.ajax({
      url: &amp;quot;/my/page&amp;quot;,
      type: &amp;quot;delete&amp;quot;
      success: function () {
        setTimeout(spy, 16);
      }
    });

    this.sandbox.server.requests[0].respond(200, {}, &amp;quot;&amp;quot;);
    this.sandbox.clock.tick(16);

    assert(spy.called);
  }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
I realize that this example gets more contrived with each iteration, but hopefully you get the point.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_5&quot;&gt;Improved 				&lt;code&gt;sinon.test&lt;/code&gt; (and by extension 				&lt;code&gt;sinon.testCase&lt;/code&gt;)&lt;/h2&gt;
&lt;p&gt;
If you've read my previous posts on Sinon.JS, or if you've used it, you may remember the 				&lt;code&gt;sinon.test&lt;/code&gt; function. It can wrap a test function to provide automatic handling of the sandbox object (previously the less capable collection object). In 0.5.0 it passed a 				&lt;code&gt;stub&lt;/code&gt; and a 				&lt;code&gt;mock&lt;/code&gt; function to the test case which were bound to the sandbox, so using them would ensure whatever was stubbed/mocked was automatically restored and verified after the test ran.
&lt;/p&gt;

&lt;p&gt;
In 0.6.0, 				&lt;code&gt;sinon.test&lt;/code&gt; use a sandbox which you can configure through 				&lt;code&gt;sinon.config&lt;/code&gt;. By default it no longer passes bound functions to the test. Instead, it exposes bound functions and - if configured to do so - 				&lt;code&gt;server&lt;/code&gt;, 				&lt;code&gt;requests&lt;/code&gt; and 				&lt;code&gt;clock&lt;/code&gt; objects to the test case on which the test function is called. Let's show our contrived example again:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.config = {
  useFakeTimers: true,
  useFakeServer: true
};

TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  &amp;quot;test something ajax-y&amp;quot;: sinon.test(function () {
    var spy = this.spy();

    jQuery.ajax({
      url: &amp;quot;/my/page&amp;quot;,
      type: &amp;quot;delete&amp;quot;
      success: function () {
        setTimeout(spy, 16);
      }
    });

    this.server.requests[0].respond(200, {}, &amp;quot;&amp;quot;);
    this.clock.tick(16);

    assert(spy.called);
  })
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As you can see, using the sandboxed test means no manual handling of fakes at all. I think this is pretty cool. You can also sandbox an entire test case this way:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;MyAjaxTest&amp;quot;, sinon.testCase({
  /* ... */
}));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This is almost the same as wrapping each test in a call to 				&lt;code&gt;sinon.test&lt;/code&gt; with one important exception - 				&lt;code&gt;setUp&lt;/code&gt; and 				&lt;code&gt;tearDown&lt;/code&gt; can use 				&lt;code&gt;this.stub&lt;/code&gt; and others along with the server and clock, too.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_5_1&quot;&gt;Configuring 				&lt;code&gt;sinon.test&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;
While the function is currently configurable, I'm not entirely happy with the configuration option names - I'd like them to be clearer, so that may change before 1.0.0. The default configuration looks like:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.config = {
  injectIntoThis: false,
  injectInto: null,
  properties: [&amp;quot;spy&amp;quot;, &amp;quot;stub&amp;quot;, &amp;quot;mock&amp;quot;, &amp;quot;clock&amp;quot;, &amp;quot;server&amp;quot;, &amp;quot;requests&amp;quot;],
  useFakeTimers: false,
  useFakeServer: false
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
In other words, XHR and timers are not faked by default, but they will be exposed to the test case if you set those options to 				&lt;code&gt;true&lt;/code&gt;. If you want to expose the properties on some other object than the 				&lt;code&gt;this&lt;/code&gt; object of the test function, set 				&lt;code&gt;injectIntoThis&lt;/code&gt; to 				&lt;code&gt;false&lt;/code&gt; and use an arbitrary object for 				&lt;code&gt;injectInto&lt;/code&gt;. For instance, if you're really keen on saving keystrokes, and can live with global properties, you can do this:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.config = {
  injectIntoThis: false,
  injectInto: this, // global object
  useFakeTimers: true,
  useFakeServer: true
};

TestCase(&amp;quot;MyAjaxTest&amp;quot;, {
  &amp;quot;test something ajax-y&amp;quot;: sinon.test(function () {
    var spy = spy();

    jQuery.ajax({
      url: &amp;quot;/my/page&amp;quot;,
      type: &amp;quot;delete&amp;quot;
      success: function () {
        setTimeout(spy, 16);
      }
    });

    server.requests[0].respond(200, {}, &amp;quot;&amp;quot;);
    clock.tick(16);

    assert(spy.called);
  })
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then you can use the properties as globals. I wouldn't recommend this approach though, but again - you get the point.
&lt;/p&gt;
	&lt;h3 id=&quot;toc213820_5_2&quot;&gt;Ensuring compatibility with 0.5.0 tests&lt;/h3&gt;
&lt;p&gt;
If you've already started using Sinon.JS 0.5.0, you may have come to depend on the 				&lt;code&gt;stub&lt;/code&gt; and 				&lt;code&gt;mock&lt;/code&gt; functions passed to test functions wrapped in 				&lt;code&gt;sinon.test&lt;/code&gt;. In that case you can use the following configuration:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.config = {
  injectIntoThis: false,
  properties: [&amp;quot;stub&amp;quot;, &amp;quot;mock&amp;quot;]
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
When both 				&lt;code&gt;injectIntoThis&lt;/code&gt; is 				&lt;code&gt;false&lt;/code&gt; and 				&lt;code&gt;injectInto&lt;/code&gt; is 				&lt;code&gt;null&lt;/code&gt;, Sinon.JS passes the named properties as arguments to the test function, in the order specified. You can still pass it all the properties and fake the server, the choice is yours.
&lt;/p&gt;
	&lt;h2 id=&quot;toc213820_6&quot;&gt;In summary&lt;/h2&gt;
&lt;p&gt;
If you got all the way through, you might be anxious to try it out. Head over to 			
									&lt;a href=&quot;http://cjohansen.no/sinon/&quot;&gt;cjohansen.no/sinon/&lt;/a&gt; to download your copy. If you have any feedback on the APIs, suggestions, found bugs, have patches or what ever, please do get in touch!
&lt;/p&gt;

&lt;p&gt;
The code is available both on 			
									&lt;a href=&quot;http://github.com/cjohansen/sinon.js&quot;&gt;Github&lt;/a&gt; and 			
									&lt;a href=&quot;http://gitorious.org/sinon&quot;&gt;Gitorious&lt;/a&gt;, for your peeking and forking pleasure. Enjoy!
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>09 Jun 2010 23:56:52 GMT</pubDate>
  <title>Sinon.JS 0.5.0 Released</title>
  <link>http://www.cjohansen.no/en/javascript/sinon_js_0_5_0_released</link>
  <guid>http://www.cjohansen.no/en/javascript/sinon_js_0_5_0_released</guid>
  <comments>http://www.cjohansen.no/en/javascript/sinon_js_0_5_0_released#comments</comments>
  <description>
    
&lt;p&gt;
I've been holding off releasing Sinon until it's &amp;quot;done&amp;quot;. Luckily, 			
									&lt;a href=&quot;http://twitter.com/augustl&quot;&gt;@augustl&lt;/a&gt; kicked me for not &amp;quot;releasing early, releasing often&amp;quot;, so I got my act together.
&lt;/p&gt;

    
&lt;p&gt;
The first version of Sinon.JS, dubbed 			
									&lt;a href=&quot;http://cjohansen.no/sinon/&quot;&gt;version 0.5.0 is available&lt;/a&gt;. There still isn't much docs available, but the page lists most of the public API, and the articles here explain a little more. I'll get to work on the docs as soon as Sinon is feature complete. Enjoy!
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>08 Jun 2010 00:01:19 GMT</pubDate>
  <title>Faking Timers and Dates with Sinon</title>
  <link>http://www.cjohansen.no/en/javascript/faking_timers_and_dates_with_sinon</link>
  <guid>http://www.cjohansen.no/en/javascript/faking_timers_and_dates_with_sinon</guid>
  <comments>http://www.cjohansen.no/en/javascript/faking_timers_and_dates_with_sinon#comments</comments>
  <description>
    
&lt;p&gt;
In addition to 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks&quot;&gt;low-level tools for stubbing and mocking&lt;/a&gt; and 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon&quot;&gt;high-level tools to integrate with test runners&lt;/a&gt;, Sinon provides a few useful utilities. This post explains the first of these, which is fake timers and Dates.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc80687_1&quot;&gt;Testing time&lt;/h2&gt;
&lt;p&gt;
Client-side JavaScript frequently utilizes 				&lt;code&gt;setTimeout&lt;/code&gt;, 				&lt;code&gt;clearTimeout&lt;/code&gt;, 				&lt;code&gt;setInterval&lt;/code&gt; and 				&lt;code&gt;clearInterval&lt;/code&gt; to defer execution. When testing code that depends on these functions you have two choices:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;Use a testing framework with async support, and make tests wait the required period of time&lt;/li&gt;

&lt;li&gt;Stub those timers&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Sinon offers a solution for the second choice, stubbing timers, which is inspired by 			
									&lt;a href=&quot;http://jsunit.net/&quot;&gt;JsUnit's JsUnitMockTimeout.js&lt;/a&gt;. The timers that ship with JsUnit provide a good start, but I find them a bit lacking:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;They always &amp;quot;mock&amp;quot; global timers as soon as the file is loaded&lt;/li&gt;

&lt;li&gt;It uses a global clock to control timers&lt;/li&gt;

&lt;li&gt;No coordination with Dates&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
So I wrote my own and included it in Sinon. Even if you don't want anything else from Sinon, you can use the timers described here - they're implemented completely independent from the rest of Sinon.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80687_2&quot;&gt;Faking timers with Sinon&lt;/h2&gt;
&lt;p&gt;
Like JsUnit, Sinon provides a clock object which you can use to manually control the passage of time (sounds nice, doesn't it?) Here's an example of how you'd use Sinon to fake 				&lt;code&gt;setTimeout&lt;/code&gt; and friends:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
    this.clock = sinon.useFakeTimers();
},

tearDown: function () {
    this.clock.restore();
},

&amp;quot;test something using timers&amp;quot;: function () {
    var stub = sinon.stub();
    setTimeout(stub, 1000);

    this.clock.tick(1000);

    assert(stub.called);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
By calling 				&lt;code&gt;sinon.useFakeTimers()&lt;/code&gt;, Sinon creates a new 				&lt;code&gt;clock&lt;/code&gt; object and returns it. The function also overrides the global timer functions with 				&lt;code&gt;clock.setTimeout&lt;/code&gt; and so on. The clock exposes a 				&lt;code&gt;tick&lt;/code&gt; method which you can pass a number of milliseconds, and any timers due for execution within the passed time-frame are called. Finally, the 				&lt;code&gt;clock.restore()&lt;/code&gt; call in 				&lt;code&gt;tearDown&lt;/code&gt; resets the global functions.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80687_3&quot;&gt;Advantages of faking time&lt;/h2&gt;
&lt;p&gt;
Using fake timers has one obvious advantage: fast tests. Rather than having the test runner sit idly around doing nothing for a bunch of milliseconds, we can instruct it to just carry out whatever it is it needs to do within the next x milliseconds, and be done with it in about a single millisecond.
&lt;/p&gt;

&lt;p&gt;
Another less obvious, but very important, advantage of faking time is clarity. Nice and clear unit tests are easier to maintain, and work better as unit level documentation. Explicitly stating the number of milliseconds to wait makes the test better at communicating its intent. This is assuming async tests are implemented using 				&lt;code&gt;wait&lt;/code&gt; and 				&lt;code&gt;resume&lt;/code&gt; style methods. If you use a 				&lt;code&gt;wait&lt;/code&gt; function that takes a number of milliseconds, the clock doesn't add much clarity.
&lt;/p&gt;

&lt;p&gt;
Note that while you can achieve the same speed by using 				&lt;code&gt;sinon.stub&lt;/code&gt; to simply stub e.g. 				&lt;code&gt;setTimeout&lt;/code&gt; and friends, you cannot achieve the same kind of clarity this way.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80687_4&quot;&gt;Faking Dates&lt;/h2&gt;
&lt;p&gt;
In addition to timers, we sometimes need to control the &amp;quot;now&amp;quot; in tests. If you have code which grabs the current time, counts elapsed time or similar using 				&lt;code&gt;new Date()&lt;/code&gt; (or 				&lt;code&gt;Date.now()&lt;/code&gt; in supporting browsers), it can sometimes be useful to control the time used by the Date constructor. Particularly if the date objects are used somehow in interaction with 				&lt;code&gt;setTimeout&lt;/code&gt; and friends.
&lt;/p&gt;

&lt;p&gt;
A practical example: For 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/test_driven_javascript_the_book&quot;&gt;the book&lt;/a&gt; I implemented a comet client which used long polling. Long polling works by making a request which is held by the server until data is available. Upon completion, a new request is immediately made. To avoid DDOS-ing the server when data is frequently available, I added an option to set a minimal interval between requests. Because the duration of a request is unknown when polling like this, elapsed time for each request was tracked using 				&lt;code&gt;new Date()&lt;/code&gt;. To write reliable and readable tests for this kind of code you have to control both the Date constructor and the timers.
&lt;/p&gt;

&lt;p&gt;
The 				&lt;code&gt;useFakeTimers&lt;/code&gt; function accepts a few optional arguments. If you don't pass it anything, it fakes out 				&lt;code&gt;setTimeout&lt;/code&gt;, 				&lt;code&gt;clearTimeout&lt;/code&gt;, 				&lt;code&gt;setInterval&lt;/code&gt; and 				&lt;code&gt;clearInterval&lt;/code&gt; and starts the clock at the current time. You can control what time the clock should start with by passing it a number: 				&lt;code&gt;sinon.useFakeTimers(0);&lt;/code&gt; starts the clock with current time 0. You can also control what methods it should fake by providing them as string arguments. So to include the Date constructor, you'll do:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
    this.clock = sinon.useFakeTimers(0, &amp;quot;setTimeout&amp;quot;, &amp;quot;clearTimeout&amp;quot;,
                                      &amp;quot;setInterval&amp;quot;, &amp;quot;clearInterval&amp;quot;, &amp;quot;Date&amp;quot;);
},

tearDown: function () {
    this.clock.restore();
},

&amp;quot;test should create fake time&amp;quot;: function () {
    var now = new Date(),

    assertEquals(0, now.getTime());
},

&amp;quot;test should pass time&amp;quot;: function () {
    this.clock.tick(10);
    var now = new Date();

    assertEquals(10, now.getTime());
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Looking at this example I'm thinking perhaps the default behavior should be to stub them all, and rather allow naming functions in those cases when you only need to fake some of them. What do you think?
&lt;/p&gt;
	&lt;h3 id=&quot;toc80687_4_1&quot;&gt;Fake dates are real dates, too&lt;/h3&gt;
&lt;p&gt;
Note that the only thing Sinon fakes with dates is how dates are created by calling 				&lt;code&gt;Date&lt;/code&gt; with no arguments. If you pass arguments to the Date constructor, it works as usual. The date objects returned from the fake constructor are real dates, and the fake constructor mirrors all available Date properties. If the browser supports it, Sinon also fakes 				&lt;code&gt;Date.now&lt;/code&gt;. That's it. Everything else is as real as can be.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80687_5&quot;&gt;Automating fake timers&lt;/h2&gt;
&lt;p&gt;
In addition to the 				&lt;code&gt;useFakeTimers&lt;/code&gt; method, I've introduced the 				&lt;code&gt;sinon.sandbox&lt;/code&gt; object. This object inherits from 				&lt;code&gt;sinon.collection&lt;/code&gt; object (			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon&quot;&gt;explained previously&lt;/a&gt;). In addition to automating collections of stubs and mocks, the sandbox also mirrors the 				&lt;code&gt;useFakeTimers&lt;/code&gt; method. By calling it through the sandbox, the timers will be restored as well when you call e.g. 				&lt;code&gt;sandbox.verifyAndRestore()&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
I'm planning to use 				&lt;code&gt;sandbox&lt;/code&gt; in place of 				&lt;code&gt;collection&lt;/code&gt; in 				&lt;code&gt;sinon.test&lt;/code&gt; to allow better integration of all of Sinon's features into any given test framework. My idea is to have an object, say 				&lt;code&gt;sinon.config&lt;/code&gt;, which controls how 				&lt;code&gt;sinon.test&lt;/code&gt; automates the use of 				&lt;code&gt;sinon.sandbox&lt;/code&gt; for every test. More on that later.
&lt;/p&gt;

&lt;p&gt;
For now you can use the sandbox as such:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
    this.sandbox = sinon.sandbox.create();
    this.sandbox.useFakeTimers();
},

tearDown: function () {
    this.sandbox.restore();
},

&amp;quot;test something&amp;quot;: function () {
    this.sandbox.stub(jQuery, &amp;quot;ajax&amp;quot;);
    this.sandbox.clock.tick(10);
    // etc
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Next up is the fake 				&lt;code&gt;XMLHttpRequest&lt;/code&gt;, which is almost there, but I need to add some way to fake data returning from the server. I have some ideas, cooked up together with 			
									&lt;a href=&quot;http://twitter.com/augustl&quot;&gt;@augustl&lt;/a&gt; which I'll get working on real soon.
&lt;/p&gt;

&lt;p&gt;
As always, feedback, criticism, ideas, questions - very welcome!
&lt;/p&gt;

&lt;p&gt;
Hook me up on Twitter: 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;@cjno&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>07 Jun 2010 22:45:14 GMT</pubDate>
  <title>Stepping Through JsTestDriver Tests</title>
  <link>http://www.cjohansen.no/en/javascript/stepping_through_jstestdriver_tests</link>
  <guid>http://www.cjohansen.no/en/javascript/stepping_through_jstestdriver_tests</guid>
  <comments>http://www.cjohansen.no/en/javascript/stepping_through_jstestdriver_tests#comments</comments>
  <description>
    
&lt;p&gt;
Sometimes it's useful to split largish JsTestDriver test suites into smaller chunks for debugging, or for slower runs. Here's a quickie little script I wrote to do just that.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc80665_1&quot;&gt;The Problem&lt;/h2&gt;
&lt;p&gt;
JsTestDriver allows you to run a specific test case (or several) or all of them. The problem is that if you want to run only a few of your cases you need to name them all, which quickly becomes bothersome.
&lt;/p&gt;

&lt;p&gt;
When would you want to run only parts of the test suite? Well, sometimes, largish test suites can totally stress out less capable browsers, like, oh say Internet Explorer 6. Running too many, or too complicated tests too quickly can cause IE to freak out in the most vile ways. Also, some kinds of test failures can cause IE (and other browsers) to behave badly.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80665_2&quot;&gt;The Solution&lt;/h2&gt;
&lt;p&gt;
When weird problems like these occur, and it's not obvious why, I like to step through the tests, one file at a time, to locate the offending test(s). Rather than manually punching in the names of the test cases I wrote a simple Ruby script. It locates all test files, then extracts all test cases from them and runs the tests, one test case at a time.
&lt;/p&gt;

&lt;p&gt;
Note that the following script uses my 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/jstdutil_a_ruby_wrapper_over_jstestdriver&quot;&gt;jstdutil gem&lt;/a&gt;, which provides the 				&lt;code&gt;jstestdriver&lt;/code&gt; command.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;#!/usr/bin/env ruby
#
# Sometimes massive failure can cause JsTestDriver to hang
# To debug those cases, it's easier to run test cases one by one
# to track which test case is causing trouble.
#
# This script also helps test less capable browsers such as IE6,
# which can get overwhelmed while trying to run too many tests too
# quickly.
#
def red(msg)
  &amp;quot;\033[31m#{msg}\033[39m&amp;quot;
end

def green(msg)
  &amp;quot;\033[32m#{msg}\033[39m&amp;quot;
end

def ok
  green(&amp;quot;OK&amp;quot;)
end

problems = []

print &amp;quot;Resetting&amp;quot;
`jstestdriver --reset`
print &amp;quot; - #{ok}\n&amp;quot;

(Dir.glob(&amp;quot;test/**/*.js&amp;quot;).collect do |test|
  File.read(test).scan(/estCase\(&amp;quot;(.+)&amp;quot;/)
end).flatten.each do |testCase|
  print testCase
  `jstestdriver --tests #{testCase}` =~ /Fails: (\d+); Errors: (\d+)/

  if $1.to_i &amp;gt; 0 || $2.to_i &amp;gt; 0
    problems &amp;lt;&amp;lt; testCase
    print &amp;quot; - &amp;quot; + red(&amp;quot;#{$1} failures, #{$2} errors&amp;quot;) + &amp;quot;\n&amp;quot;
  else
    print &amp;quot; - #{ok}\n&amp;quot;
  end
end

if problems.count &amp;gt; 0
  puts red(&amp;quot;Some test cases had failures and/or errors&amp;quot;)
  puts problems.join(&amp;quot;\n&amp;quot;)
else
  puts green(&amp;quot;No problems&amp;quot;)
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Note that the script scans for &amp;quot;estCase&amp;quot;. The reason for this is that sometimes I use JsTestDriver's 				&lt;code&gt;TestCase&lt;/code&gt; function, and sometimes I use a custom 				&lt;code&gt;testCase&lt;/code&gt;, which wraps the test case in a 				&lt;code&gt;sinon.testCase&lt;/code&gt; call.
&lt;/p&gt;

&lt;p&gt;
The following is an example run stepping through Sinon's tests:
&lt;/p&gt;

&lt;div class=&quot;object-center&quot;&gt;&lt;div class=&quot;image&quot;&gt;
  	
	
	
	
	
	
				&lt;img src=&quot;/var/cj_no/storage/images/media/images/stepping_through_sinon_s_tests_2/80682-1-nor-NO/stepping_through_sinon_s_tests_2.png&quot; width=&quot;504&quot; height=&quot;405&quot; alt=&quot;&quot; /&gt;	
	&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;
Well, there you have it. Put the script in e.g. 				&lt;code&gt;step-tests&lt;/code&gt;, make it executable, and run whenever you're having weird problems occurring.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>27 May 2010 00:22:08 GMT</pubDate>
  <title>Higer-level Stubbing and Mocking Tools in Sinon</title>
  <link>http://www.cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon</link>
  <guid>http://www.cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon</guid>
  <comments>http://www.cjohansen.no/en/javascript/higer_level_stubbing_and_mocking_tools_in_sinon#comments</comments>
  <description>
    
&lt;p&gt;
Having covered the basic Sinon interface in one and a half posts I want to show you some of the higher-level tools Sinon brings to the table to reduce the amount of ceremony required to add stubs and mocks to your JavaScript tests. Hopefully, these tools will make it dead simple to properly integrate Sinon with any xUnit style test framework.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc80451_1&quot;&gt;Collections&lt;/h2&gt;
&lt;p&gt;
As previously discussed, stubbing and mocking shared/global objects requires some scaffolding to avoid ripple effects from stubs and mocks leaking between tests. Basically this means having to add a call to 				&lt;code&gt;restore()&lt;/code&gt; on each stub in the 				&lt;code&gt;tearDown&lt;/code&gt; method.
&lt;/p&gt;

&lt;p&gt;
Additionally, if you set expectations on more than a single mock in one test you have a possibly unsolvable problem on your hands: If the first mock fails its 				&lt;code&gt;verify()&lt;/code&gt; call, it will throw an exception, meaning that further mocks are never verified and thus not restored. This problem can be circumvented by restoring mocks in 				&lt;code&gt;tearDown&lt;/code&gt; as well, but this quickly becomes bothersome.
&lt;/p&gt;

&lt;p&gt;
A final problem is this: If not all tests stub and/or mock the same methods, you have to check that a given method has a 				&lt;code&gt;restore&lt;/code&gt; property before calling it from 				&lt;code&gt;tearDown&lt;/code&gt;. That's an if statement in your test case, and it should make you throw up.
&lt;/p&gt;

&lt;p&gt;
Sinon offers collections to deal with these issues.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80451_1_1&quot;&gt;Stub collections&lt;/h3&gt;
&lt;p&gt;
A stub collection is created by calling 				&lt;code&gt;sinon.collection.create()&lt;/code&gt;. The resulting object has a 				&lt;code&gt;stub()&lt;/code&gt; method which works exactly like 				&lt;code&gt;sinon.stub()&lt;/code&gt;, only a reference to the resulting stub function is kept by the collection. This means you can create the collection in 				&lt;code&gt;setUp&lt;/code&gt;, and call 				&lt;code&gt;restore()&lt;/code&gt; on it in 				&lt;code&gt;tearDown&lt;/code&gt; to restore all stubs back to normal.
&lt;/p&gt;

&lt;p&gt;
The following is an example from the previous post, updated to use a collection:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
  this.fakes = sinon.collection.create();
},

tearDown: function () {
  this.fakes.restore();
},

&amp;quot;test using XMLHttpRequest open should be called before send&amp;quot;: function () {
  var open = this.fakes.stub(XMLHttpRequest.prototype, &amp;quot;open&amp;quot;);
  var send = this.fakes.stub(XMLHttpRequest.prototype, &amp;quot;send&amp;quot;);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);

  assert(open.calledBefore(send));
  assert(send.calledAfter(open));
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The collections can pretty easily be built into your test framework of choice, but as you will see shortly, Sinon has more in stock.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80451_1_2&quot;&gt;Mock collections&lt;/h3&gt;
&lt;p&gt;
Mocks need to have their 				&lt;code&gt;verify()&lt;/code&gt; method called. Collections support this as well:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
  this.fakes = sinon.collection.create();
},

tearDown: function () {
  this.fakes.verify();
},

&amp;quot;test should always pass argument to send&amp;quot;: function () {
  this.fakes.mock(XMLHttpRequest.prototype).expects(&amp;quot;send&amp;quot;).withArgs(null);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now that the mock is created through the collection the test no longer needs a local reference to it - it's verified &amp;quot;automatically&amp;quot; in the 				&lt;code&gt;tearDown&lt;/code&gt; method.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80451_1_3&quot;&gt;Mix and match stubs and mocks&lt;/h3&gt;
&lt;p&gt;
Stubs need to be reset while mocks need to be verified. Actually, mocks need to be reset as well, but 				&lt;code&gt;verify&lt;/code&gt; does it for them. Collections have a third method, 				&lt;code&gt;verifyAndRestore&lt;/code&gt;, which verifies all mocks, catches any exceptions, restores all fakes and &lt;b&gt;then&lt;/b&gt; throws any expectation failures. Observe:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;setUp: function () {
  this.fakes = sinon.collection.create();
},

tearDown: function () {
  this.fakes.verifyAndRestore();
},

&amp;quot;test should always pass argument to send&amp;quot;: function () {
  this.fakes.stub(XMLHttpRequest.prototype);
  this.fakes.mock(XMLHttpRequest.prototype).expects(&amp;quot;send&amp;quot;).withArgs(null);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
No matter what happens to this test, the 				&lt;code&gt;XMLHttpRequest&lt;/code&gt; object is restored to its native state when it's done.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80451_2&quot;&gt;Automating collections&lt;/h2&gt;
&lt;p&gt;
While a lot better than manually juggling all the stubs and mocks, collections still require a tiny ceremony. Sinon can take care of this for you by wrapping the test method in a call to 				&lt;code&gt;sinon.test&lt;/code&gt;. When you do so, Sinon creates a collection, binds the 				&lt;code&gt;stub&lt;/code&gt; and 				&lt;code&gt;mock&lt;/code&gt; methods on it and passes them as arguments to the test method. When the test is done (or if it fails), Sinon verifies-and-restores all the fakes before returning control to the test runner.
&lt;/p&gt;

&lt;p&gt;
Let's revisit the ajax example:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should always pass argument to send&amp;quot;: sinon.test(function (stub, mock) {
  stub(XMLHttpRequest.prototype);
  mock(XMLHttpRequest.prototype).expects(&amp;quot;send&amp;quot;).withArgs(null);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);
})&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now we're getting somewhere. We're down to a single method call and two arguments to completely automate mock verification and global stub restoration.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80451_2_1&quot;&gt;Sinon test cases&lt;/h3&gt;
&lt;p&gt;
One unfortunate consequence of using 				&lt;code&gt;sinon.test&lt;/code&gt; is that fakes cannot be shared from 				&lt;code&gt;setUp&lt;/code&gt;, as it does not have access to the bound 				&lt;code&gt;stub&lt;/code&gt; and 				&lt;code&gt;mock&lt;/code&gt; functions.
&lt;/p&gt;

&lt;p&gt;
Sinon has an answer to this problem as well. By wrapping the entire test case in a call to 				&lt;code&gt;sinon.testCase&lt;/code&gt;, Sinon gives every test method the 				&lt;code&gt;sinon.test()&lt;/code&gt; treatment, and takes over running 				&lt;code&gt;setUp&lt;/code&gt; and 				&lt;code&gt;tearDown&lt;/code&gt;. This way, stubs and mocks can be created in set up to share between tests, but still be dismantled between each run.
&lt;/p&gt;

&lt;p&gt;
The following example is our running example used with 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/&quot;&gt;JsTestDriver&lt;/a&gt;:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;TestCase(&amp;quot;AjaxTest&amp;quot;, sinon.testCase({
  setUp: function (stub, mock) {
    stub(XMLHttpRequest.prototype);
  },

  &amp;quot;test should always pass argument to send&amp;quot;: function (stub, mock) {
    mock(XMLHttpRequest.prototype).expects(&amp;quot;send&amp;quot;).withArgs(null);

    jQuery.ajax(&amp;quot;/some/url&amp;quot;);
  },

  &amp;quot;test using XMLHttpRequest open should be called before send&amp;quot;: function () {
    jQuery.ajax(&amp;quot;/some/url&amp;quot;);

    var xhr = XMLHttpRequest.prototype;
    assert(xhr.open.calledBefore(xhr.send)); // or...
    assert(xhr.send.calledAfter(xhr.open));
  }
}));&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc80451_2_2&quot;&gt;What needs work?&lt;/h3&gt;
&lt;p&gt;
One of the goals of Sinon is to be completely test framework agnostic - at least within the xUnit style frameworks. I've tried to satisfy this requirement by separating concerns as much as possible, and by layering high-level helpers such that any given framework can choose its entry level. Currently I've employed defaults that favor JsTestDriver, simply because it's the test runner I'm currently using.
&lt;/p&gt;

&lt;p&gt;
Going forward I imagine making some of the behavior of the above tools configurable to adapt to a wider range of frameworks. For instance, there could possibly be some kind of configuration telling Sinon where to expose the bound 				&lt;code&gt;stub&lt;/code&gt; and 				&lt;code&gt;mock&lt;/code&gt; functions. Passed as arguments to tests is one way to do it - binding them to the test case object another. Hell, maybe even offer to expose them into the global environment for the folks who really want that.
&lt;/p&gt;

&lt;p&gt;
Any feedback on these things would be greatly appreciated! I'm very open to feedback, both good and bad - but preferably constructive - so give it your best.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80451_3&quot;&gt;Assertions&lt;/h2&gt;
&lt;p&gt;
The final piece of cosmetics for spy behavior verification is Sinon's assertions. Using custom assertions in place of the spy interface has two main benefits:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;Stubs and mocks appear to be natives in the test framework, good for consistency.&lt;/li&gt;

&lt;li&gt;Assertions can fail with much more detailed messages, making the source of errors easier to track down.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
The following assertions mirror the methods available on spies, and I won't explain them in detail again. Please refer to 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks&quot;&gt;the original post&lt;/a&gt; for detailed explanations. When an assertion accepts a &amp;quot;spy&amp;quot; as argument, it means you can pass it spies, stubs and mocks as they all implement the spy interface. In practice, you'll be using assertions with stubs.
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.called(spy)&lt;/code&gt;&lt;br /&gt; Assert that the spy was called.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.calledOrder(spy1, spy2, ...)&lt;/code&gt;&lt;br /&gt; Pass in any number of spies to assert they were called in the specified order.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.callCount(spy, num)&lt;/code&gt;&lt;br /&gt; Assert that the spy was called the specified number of times.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.calledOn(spy, thisObj)&lt;/code&gt;&lt;br /&gt; Assert that the spy was called with 				&lt;code&gt;thisObj&lt;/code&gt; as 				&lt;code&gt;this&lt;/code&gt; at least once.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.alwaysCalledOn(spy, thisObj)&lt;/code&gt;&lt;br /&gt; Same as above, only match all calls.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.calledWith(spy, arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Assert that the spy was called with the provided arguments (and possibly others) at least once.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.alwaysCalledWith(spy, arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Assert that the spy was always called with the provided arguments (and possibly others).&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.calledWithExactly(spy, arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Assert that the spy was called with the provided arguments, and nothing else, at least once.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.alwaysCalledWithExactly(spy, arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Assert that the spy was always called with the provided arguments, and nothing else.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.threw(spy[, exception])&lt;/code&gt;&lt;br /&gt; As the spy method - exception is optional and can be a string or an exception object.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;sinon.assert.alwaysThrew(spy[, exception])&lt;/code&gt;&lt;br /&gt; As above, only match all calls.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Let's revisit our ajax example again, this time using assertions to verify the test:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test open should be called before send&amp;quot;: sinon.test(function (stub, mock) {
  var open = stub(XMLHttpRequest.prototype, &amp;quot;open&amp;quot;);
  var send = stub(XMLHttpRequest.prototype, &amp;quot;send&amp;quot;);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);

  sinon.assert.callOrder(open, send);
})&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc80451_3_1&quot;&gt;Mixing assertions in on other objects&lt;/h3&gt;
&lt;p&gt;
The only thing sticking out in this test is the namespace - JsTestDriver uses global assertions. To better fit in, we can instruct Sinon to expose the assertions onto another object, optionally renaming assertions by prefixing them with &amp;quot;assert&amp;quot;. Observe:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;
// Before loading tests
// this - global object in global scope
// true - map names to include the assert prefix
sinon.assert.expose(this, true);

TestCase(&amp;quot;AjaxTest&amp;quot;, sinon.testCase({
  &amp;quot;test open should be called before send&amp;quot;: function (stub, mock) {
    var open = stub(XMLHttpRequest.prototype, &amp;quot;open&amp;quot;);
    var send = stub(XMLHttpRequest.prototype, &amp;quot;send&amp;quot;);

    jQuery.ajax(&amp;quot;/some/url&amp;quot;);

    assertCallOrder(open, send);
  }
}));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Beautiful - looks entirely like a native JsTestDriver assertion.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80451_3_2&quot;&gt;Failing assertions&lt;/h3&gt;
&lt;p&gt;
In order for assertion failures to blend properly with the test framework's assertions, they need a common concept of failure. Sinon currently offers two ways to tweak this. The default behavior is to throw an 				&lt;code&gt;AssertError&lt;/code&gt; exception. Incidentally, this is exactly what JsTestDriver does, meaning that the above example already works smoothly with it.
&lt;/p&gt;

&lt;p&gt;
Other runners may define failure differently. To change the kind of assertion thrown, set the string property 				&lt;code&gt;sinon.assert.failException&lt;/code&gt; to the desired type. If throwing an exception isn't compatible with the test runner's way of failing you can override 				&lt;code&gt;sinon.assert.fail&lt;/code&gt; which is a function. The default one looks like this:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;function fail(message) {
  var error = new Error(message);
  error.name = this.failException || assert.failException;
  throw error;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
As I mentioned this already matches the way JsTestDriver fails assertions. What's more is that JsTestDriver already has a global 				&lt;code&gt;fail&lt;/code&gt; function. To avoid overwriting it, you can provide a third argument to 				&lt;code&gt;sinon.assert.expose&lt;/code&gt;, which is a boolean specifying whether or not 				&lt;code&gt;failException&lt;/code&gt; and 				&lt;code&gt;fail&lt;/code&gt; should be exported as well. Pass 				&lt;code&gt;false&lt;/code&gt; to leave them behind.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80451_4&quot;&gt;In conclusion&lt;/h2&gt;
&lt;p&gt;
That's about it for now. I think, and hope that these tools will make integrating Sinon with your favorite test framework a breeze. Once I've gotten the first release out the door I will start actually integrating it with more than the one test framework I've tried so far to discover areas where my assumptions won't hold.
&lt;/p&gt;

&lt;p&gt;
If you have any ideas on how to improve the interface or just general comments about Sinon, keep it coming! In the next and last (for now) post on Sinon I'll cover its utilities for testing timers and ajax requests.
&lt;/p&gt;

&lt;p&gt;
As always, I'm 			
									&lt;a href=&quot;http://twitter.com/cjno/&quot;&gt;@cjno on Twitter&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>26 May 2010 23:01:59 GMT</pubDate>
  <title>Test Spies, Stubs and Mocks - Part 1.5</title>
  <link>http://www.cjohansen.no/en/javascript/test_spies_stubs_and_mocks_part_1_5</link>
  <guid>http://www.cjohansen.no/en/javascript/test_spies_stubs_and_mocks_part_1_5</guid>
  <comments>http://www.cjohansen.no/en/javascript/test_spies_stubs_and_mocks_part_1_5#comments</comments>
  <description>
    
&lt;p&gt;
While 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks&quot;&gt;presenting the core Sinon interface yesterday&lt;/a&gt; i unintentionally left out parts of the API. To make up for the mistake, here are the missing pieces.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc80441_1&quot;&gt;Spies&lt;/h2&gt;
&lt;p&gt;
In the original post I wrote about the data spies collect in arrays as well as the methods spies expose to interact with the recorded call data. However, you might have recognized a gap in the interface - you can either match any one call, or all of them. If you need more fine-grained control, spies have a 				&lt;code&gt;getCall(num)&lt;/code&gt; method which retrieves a specific call, which in turn supports a similar interface to that of the spies themselves.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80441_1_1&quot;&gt;Behavior verification for individual calls&lt;/h3&gt;
&lt;p&gt;
Given the original example:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.spy(jQuery, &amp;quot;ajax&amp;quot;);
jQuery.getJSON(&amp;quot;/some/data&amp;quot;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
You can retrieve the first (and in this case, only) call with:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var call = jQuery.ajax.getCall(0);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then you can match against its recorded data using:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;call.calledWith(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Pass in any number of arguments, and the method returns 				&lt;code&gt;true&lt;/code&gt; if the call received the specified arguments. The list of arguments does not need to be exhaustive - you can provide the first argument, and the method will return 				&lt;code&gt;true&lt;/code&gt; if the call received this argument as its first (possibly with additional arguments).&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;call.calledWithExactly(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; If you need to know if the call received certain arguments, and nothing but those certain arguments, this method is the strict variation of 				&lt;code&gt;calledWith(arg1, arg2, ...)&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;returned(returnValue)&lt;/code&gt;&lt;br /&gt; Returns 				&lt;code&gt;true&lt;/code&gt; if the call returned the specified value.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;threw(exceptionOrType)&lt;/code&gt;&lt;br /&gt; If no arguments are passed, the method returns 				&lt;code&gt;true&lt;/code&gt; if the call threw an exception. If a string argument is passed, it returns 				&lt;code&gt;true&lt;/code&gt; if the call threw an exception of the provided type, such as 				&lt;code&gt;&amp;quot;TypeError&amp;quot;&lt;/code&gt;. Finally, if an exception object is passed, 				&lt;code&gt;true&lt;/code&gt; is returned if the call threw this exact exception object (not likely to be used much, but there for completeness).&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;calledOn(thisObj)&lt;/code&gt;&lt;br /&gt; Returns 				&lt;code&gt;true&lt;/code&gt; if the call was made with the specified object as 				&lt;code&gt;this&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Basically, each call support the same exact interface as the stub, save for the &amp;quot;always&amp;quot; variation. When called on a specific call, the methods naturally match only that one call.
&lt;/p&gt;

&lt;p&gt;
These methods are used extensively in the implementation of spies, but I'd be careful with using them extensively in tests. Targeting specific calls like this may cause your tests to be unnecessarily implementation specific, thus brittle.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80441_1_2&quot;&gt;Call order&lt;/h3&gt;
&lt;p&gt;
I also left out two methods on spies: 				&lt;code&gt;calledBefore&lt;/code&gt; and 				&lt;code&gt;calledAfter&lt;/code&gt;. Both of these can come in handy in certain situation, but are also subject to the same reservation I just mentioned: exaggerated use will cause too implementation specific tests.
&lt;/p&gt;

&lt;p&gt;
To keep with the jQuery examples, the following test could be imagined to be part of jQuery's test case for the 				&lt;code&gt;ajax&lt;/code&gt; method.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test using XMLHttpRequest open should be called before send&amp;quot;: function () {
  var open = sinon.stub(XMLHttpRequest.prototype, &amp;quot;open&amp;quot;);
  var send = sinon.stub(XMLHttpRequest.prototype, &amp;quot;send&amp;quot;);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);

  assert(open.calledBefore(send));
  assert(send.calledAfter(open));
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The two asserts in the above test case are basically testing the same, which one to use is a matter of preference.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80441_2&quot;&gt;Stubs&lt;/h2&gt;
&lt;p&gt;
I left out a little detail from the stub interface as well. As you may have noticed, stubs, mocks and spies all are function-centric in Sinon. From my own experience, I very rarely need to fake entire objects. A single test rarely need to fake out more than a handful of functions at a time, so focusing on functions makes sense.
&lt;/p&gt;

&lt;p&gt;
For those rare cases where you really want to stub all the methods of an object, you can use the 				&lt;code&gt;sinon.stub()&lt;/code&gt; function with only an object as first argument. Doing so instructs Sinon to stub out all the methods. If you need you can fine-tune the stubs later, as seen in the following example:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;
sinon.stub(XMLHttpRequest.prototype);
XMLHttpRequest.prototype.getResponseHeader.returns(&amp;quot;&amp;quot;);

jQuery.ajax(&amp;quot;/some/url&amp;quot;);

// ...&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Here, Sinon stubs all the methods on 				&lt;code&gt;XMLHttpRequest.prototype&lt;/code&gt;. This means they're all stub functions now, allowing you call the stub and spy methods on them directly to further tweak their behavior.
&lt;/p&gt;

&lt;p&gt;
There's no equivalent to this for mocks. If you really want to create mock expectations on all the methods of an object in a test you might want to reconsider your test design - chances are it's doing more than it should. I have no plans to implement a way to mock and set expectations on more than a single method at a time as I don't see a viable use case for it.
&lt;/p&gt;

&lt;p&gt;
Note that you can mix and match as well. If you want to silence an object and set an expectation on one or a few of the methods, you can do that:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should always pass argument to send&amp;quot;: function () {
  sinon.stub(XMLHttpRequest.prototype);
  var mock = sinon.mock(XMLHttpRequest.prototype);

  // If no argument is passed to send on GET requests, FF &amp;lt;= v3.0 will
  // throw an exception
  mock.expects(&amp;quot;send&amp;quot;).once().withArgs(null);

  jQuery.ajax(&amp;quot;/some/url&amp;quot;);

  mock.verify();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The above test silences all the native XMLHttpRequest methods, and then overrides the stub created for 				&lt;code&gt;send&lt;/code&gt; with a mock expectation that expects an argument to be passed.
&lt;/p&gt;

&lt;p&gt;
That's about it. In the next post, which is the real second post, I'll discuss integration with xUnit style testing frameworks.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>25 May 2010 23:18:33 GMT</pubDate>
  <title>JavaScript Test Spies, Stubs and Mocks</title>
  <link>http://www.cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks</link>
  <guid>http://www.cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks</guid>
  <comments>http://www.cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks#comments</comments>
  <description>
    
&lt;p&gt;
One of the things coming out of me recently 			
									&lt;a href=&quot;http://cjohansen.no/en/javascript/test_driven_javascript_the_book&quot;&gt;writing a book&lt;/a&gt; (apart from, you know, 			
									&lt;a href=&quot;http://www.amazon.com/dp/0321683919&quot;&gt;a book&lt;/a&gt;) is a JavaScript stubbing and mocking library (still in the making) called Sinon. This is the first of a total of three posts giving a preview on the API. Hopefully some of you want to share your ideas and feedback on it.
&lt;/p&gt;

    
&lt;p&gt;
In this post we'll walk through the core of the library; spies, stubs and mocks. I'll cover the basic concept of the library and show most of the related API.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_1&quot;&gt;Goals of Sinon&lt;/h2&gt;
&lt;p&gt;
So, why write another stubbing and mocking library? There are already a few out there, and several testing libraries ship with built-in stubs and mocks. I originally wrote Sinon for the book, with the intention of using it for one of the &amp;quot;TDD by example&amp;quot; chapters. That didn't happen, but I still used it as an example of using a library for stubbing and mocking (as opposed to manual stubbing, which works for most simple use cases).
&lt;/p&gt;

&lt;p&gt;
I had some design requirements for such a library:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;&lt;b&gt;Standalone&lt;/b&gt; There's no reason to tie stubbing and mocking to a specific testing library. Granted, some aspects can be automated when doing so, but such integration can be provided for standalone libraries as well.&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Minimal global footprint&lt;/b&gt; The test environment is the last environment you want massive global pollution. The stub and mock API should live within a single object.&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Easy to use&lt;/b&gt; That's probably a given, but some of the mocking solutions I've seen requires unnecessary amounts of scaffolding to get going.&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Easy to integrate&lt;/b&gt; Making up for being standalone, I want the (minimal) scaffolding to be easy to automate with any testing library.&lt;/li&gt;

&lt;li&gt;&lt;b&gt;CommonJS compliant&lt;/b&gt; Work both in browsers and on the server using CommonJS modules.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Sinon passes these requirements. It's standalone, it lives entirely within the 				&lt;code&gt;sinon&lt;/code&gt; object, has a (hopefully) simple API and provides lots of tools to reduce the required amount of scaffolding. This post focuses on the API, and I'll post a follow-up soon covering the integration part.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_2&quot;&gt;Status&lt;/h2&gt;
&lt;p&gt;
Currently, the Sinon core, covered in this post, is functional but the library as a whole is not feature complete, neither is the API frozen. By sharing info about it at this point I hope to lower the bar for providing feedback and suggestions. The main shortcoming at this point, however is documentation. I will not do a &amp;quot;release&amp;quot; until I have proper documentation. This post, and the two following it is a start.
&lt;/p&gt;

&lt;p&gt;
Enough chatter, on to the code.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_3&quot;&gt;Test spies&lt;/h2&gt;
&lt;p&gt;
A 			
									&lt;a href=&quot;http://xunitpatterns.com/Test%20Spy.html&quot;&gt;test spy&lt;/a&gt; is an object that records its interaction with other objects throughout the code base. When deciding if a test was successful based on the state of available objects alone is not sufficient, we can use test spies and make assertions on things such as the number of calls, arguments passed to specific functions, return values and more.
&lt;/p&gt;

&lt;p&gt;
Sinon implements spies as functions that wrap other functions and records each and every call, including the value of 				&lt;code&gt;this&lt;/code&gt;, arguments, return value and any exceptions thrown. It is possible to spy on live methods without interfering with their normal behavior, although in practice you will rarely create a spy directly. Both stubs and mocks implement the spy interface.
&lt;/p&gt;

&lt;p&gt;
Spies have a few properties, and a handful of methods. This is how you'd use a spy on jQuery's 				&lt;code&gt;ajax&lt;/code&gt; method:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.spy(jQuery, &amp;quot;ajax&amp;quot;);
jQuery.getJSON(&amp;quot;/some/data&amp;quot;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Doing this does not interfere with normal operation of 				&lt;code&gt;jQuery.ajax&lt;/code&gt;, but it wraps the method and records data.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80380_3_1&quot;&gt;Properties&lt;/h3&gt;
&lt;p&gt;
The following are properties exposed by spies, and their corresponding values for the above example.
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;				&lt;code&gt;jQuery.ajax.called&lt;/code&gt; boolean, 				&lt;code&gt;true&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;jQuery.ajax.callCount&lt;/code&gt; number, 				&lt;code&gt;1&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;jQuery.ajax.calledOnce&lt;/code&gt; boolean, convenience, 				&lt;code&gt;true&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;jQuery.ajax.calledTwice&lt;/code&gt; boolean, convenience, 				&lt;code&gt;false&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;jQuery.ajax.calledThrice&lt;/code&gt; boolean, convenience, 				&lt;code&gt;false&lt;/code&gt;&lt;/li&gt;

&lt;/ul&gt;
	&lt;h3 id=&quot;toc80380_3_2&quot;&gt;Call data&lt;/h3&gt;
&lt;p&gt;
Spies store data about calls in four arrays. If you prefer to keep things low-level, these are all you need.
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.args&lt;/code&gt;&lt;br /&gt;A nested array of arguments received by the spy. To retrieve the first argument of the first call, you'd do 				&lt;code&gt;jQuery.ajax.args[0][0]&lt;/code&gt; where the first 0 is the call number and the second is the argument index.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.returnValues&lt;/code&gt;&lt;br /&gt;An array of each call's return value. To retrieve the value returned the first time the spy was called, you'd do 				&lt;code&gt;jQuery.ajax.returnValues[0]&lt;/code&gt;. For calls that don't have an explicit return value, the array stores 				&lt;code&gt;undefined&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.exceptions&lt;/code&gt;&lt;br /&gt;An array of exceptions thrown by the spy. If the spy does not throw an exception in any given call, 				&lt;code&gt;undefined&lt;/code&gt; is stored in the array. The array always contains one entry per call, regardless of whether it throws or not.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.thisValues&lt;/code&gt;&lt;br /&gt;An array of 				&lt;code&gt;this&lt;/code&gt; values. For each call, the spy stores the value of 				&lt;code&gt;this&lt;/code&gt; in this array, which can be useful when testing that functions are passed callbacks bound to a specific object, or that callbacks are called with the right context using 				&lt;code&gt;call&lt;/code&gt; or 				&lt;code&gt;apply&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;
	&lt;h3 id=&quot;toc80380_3_3&quot;&gt;Methods&lt;/h3&gt;
&lt;p&gt;
If you prefer to keep things on a low level, the four above arrays will provide you with everything you need to know about a spy's travel through a certain code path. If, however, you're more like me, and like high-level method calls that help tests clearly state their intent, you might be interested in the methods provided by the test spies.
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.calledWith(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Pass in any number of arguments, and the method returns 				&lt;code&gt;true&lt;/code&gt; if it was called at least once with the specified arguments. The list of arguments does not need to be exhaustive - you can provide the first argument, and the method will return 				&lt;code&gt;true&lt;/code&gt; if any one call received this argument as its first (possibly with additional arguments).&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.calledWithExactly(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; If you need to know if a function received certain arguments, and nothing but those certain arguments, this method is the strict variation of 				&lt;code&gt;calledWith(arg1, arg2, ...)&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.alwaysCalledWith(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Same as 				&lt;code&gt;calledWith(arg1, arg2, ...)&lt;/code&gt;, only it requires all the calls to the spy to match the arguments.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;jQuery.ajax.alwaysCalledWithExactly(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt;Same as 				&lt;code&gt;calledWithExactly(arg1, arg2, ...)&lt;/code&gt;, only it requires all the calls to the spy to match the arguments and nothing but them.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;returned(returnValue)&lt;/code&gt;&lt;br /&gt; Returns 				&lt;code&gt;true&lt;/code&gt; if the spy returned the specified return value.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;alwaysReturned(returnValue)&lt;/code&gt;&lt;br /&gt; As above, only match all calls.&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;

				&lt;code&gt;threw(exceptionOrType)&lt;/code&gt;&lt;br /&gt; If no arguments are passed, the method returns 				&lt;code&gt;true&lt;/code&gt; if the spy threw an exception (in any one call). If a string argument is passed, it returns 				&lt;code&gt;true&lt;/code&gt; if the spy threw an exception of the provided type, such as 				&lt;code&gt;&amp;quot;TypeError&amp;quot;&lt;/code&gt;. Finally, if an exception object is passed, 				&lt;code&gt;true&lt;/code&gt; is returned if the spy threw this exact exception object (not likely to be used much, but there for completeness).
&lt;/p&gt;

&lt;p&gt;

 I'm thinking that this method probably should accept two strings, denoting&lt;br /&gt; the type and message expected of the thrown exception. Possibly it could even accept a string type and regular expression to match the message. What do you think?
&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;alwaysThrew(...)&lt;/code&gt;&lt;br /&gt; As above, only match all calls.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;calledOn(thisObj)&lt;/code&gt;&lt;br /&gt; Returns 				&lt;code&gt;true&lt;/code&gt; if the method was called with the specified object as 				&lt;code&gt;this&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;alwaysCalledOn(...)&lt;/code&gt;&lt;br /&gt; As above, only match all calls.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
In addition to these methods, spies have a special method to &amp;quot;unwrap&amp;quot; the method they are spying on:
&lt;/p&gt;

&lt;p&gt;
				&lt;code&gt;jQuery.ajax.restore();&lt;/code&gt;
&lt;/p&gt;

&lt;p&gt;
This unwraps and restores the original method. To avoid spies leaking from test to test, all spies can be restored in e.g. a test case's 				&lt;code&gt;tearDown&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Using these methods with assertions can provide pretty good readability in tests:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should register click events for buttons&amp;quot;: function () {
  sinon.spy(dom, &amp;quot;addEventHandler&amp;quot;);
  var buttons = dom.get(&amp;quot;div.button&amp;quot;, this.form);

  this.feedback.setForm(this.form);

  assert(dom.addEventHandler.calledWith(buttons[0], &amp;quot;click&amp;quot;));
  assert(dom.addEventHandler.calledWith(buttons[1], &amp;quot;click&amp;quot;));
  assert(dom.addEventHandler.calledWith(buttons[2], &amp;quot;click&amp;quot;));
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This test uses some homegrown tools in place of a library. It verifies that all buttons inside a form has click event handlers added to them. Note that the assertions only check the two first arguments - the element and event name, not the handler (which is covered by a separate test). Reviewing this example I realize I should've used event delegation in this case, but oh well...
&lt;/p&gt;

&lt;p&gt;
Sinon has some even more high-level tools for working with spies, but I'll cover them in a later post when I show you Sinon's offerings for test library integration.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_4&quot;&gt;Stubs&lt;/h2&gt;
&lt;p&gt;
			
									&lt;a href=&quot;http://xunitpatterns.com/Test%20Stub.html&quot;&gt;Test stubs&lt;/a&gt; are fake objects with pre-programmed behavior. They are typically used for one of two reasons:
&lt;/p&gt;

&lt;ol&gt;

&lt;li&gt;To avoid some inconvenient interface - for instance to avoid making actual requests to a server from tests.&lt;/li&gt;

&lt;li&gt;To feed the system with known data, forcing a specific code path.&lt;/li&gt;

&lt;/ol&gt;

&lt;p&gt;
JavaScript has first class functions, which will take you a long way. Consider the following pseudo-code example:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should call event handler&amp;quot;: function () {
  var handler = function () { handler.called = true; };
  var myElement = document.getElementsByTagName(&amp;quot;a&amp;quot;)[0];

  dom.addEventListener(myElement, &amp;quot;mouseover&amp;quot;, handler);
  dom.fireEvent(myElement, &amp;quot;mouseover&amp;quot;);

  assertTrue(handler.called);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Because JavaScript functions are so versatile, most simple uses for stubs are easy to hand roll. However, after doing that for a while you realize that using a library can possibly reduce manual scaffolding, especially when stubbing global interfaces, such as the previous example of 				&lt;code&gt;jQuery.ajax&lt;/code&gt;.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80380_4_1&quot;&gt;Creating stubs&lt;/h3&gt;
&lt;p&gt;
Sinon provides a simple API to build stubs. To create a stub, simply call 				&lt;code&gt;sinon.stub()&lt;/code&gt;. It returns an &amp;quot;empty&amp;quot; function which in addition to support methods to instruct its behavior supports the aforementioned spy API. Thus, the above example could be solved with Sinon as follows:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should call event handler&amp;quot;: function () {
  var handler = sinon.stub();
  var myElement = document.getElementsByTagName(&amp;quot;a&amp;quot;)[0];

  dom.addEventListener(myElement, &amp;quot;mouseover&amp;quot;, handler);
  dom.fireEvent(myElement, &amp;quot;mouseover&amp;quot;);

  assertTrue(handler.called);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Only slightly easier, but this is one of the easiest cases to support. Because it supports the entire spy interface we could have also checked the number of counts, 				&lt;code&gt;this&lt;/code&gt;, arguments and more.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80380_4_2&quot;&gt;Stubs methods&lt;/h3&gt;
&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;returns(returnValue)&lt;/code&gt;&lt;br /&gt; Causes the stub to return the specified value.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;throws(exception)&lt;/code&gt;&lt;br /&gt; Causes the stub to throw an exception. If the argument is a string, it specifies the type of exception to throw. If it's an object, it throws the argument untouched. If no argument is provided, an 				&lt;code&gt;Error&lt;/code&gt; is thrown (when called).&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;
				&lt;code&gt;callsArg(index)&lt;/code&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;b&gt;Will probably change!&lt;/b&gt; This method causes the stub to immediately call functions passed to it. The argument specifies which argument number (0 based index) to treat as a callback. I'm not happy with the name or the numeric index for this method. Suggestions are welcome.
&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;
				&lt;code&gt;callsArgWith(index, arg1, arg2, ...)&lt;/code&gt;
&lt;/p&gt;

&lt;p&gt;
&lt;b&gt;Will probably change!&lt;/b&gt; Like the above method, only here you can also provide arguments the stub will pass to the callback. As with 				&lt;code&gt;callsArg&lt;/code&gt;, I'm not sure about the signature of this method. I want something more intuitive, but this is the best I've come up with so far.
&lt;/p&gt;
&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
The last two methods can prove very helpful once I get them right. I'd also like for the stub to be able to call callbacks passed as part of an &amp;quot;options&amp;quot; object. I haven't figured out a reasonably short and clear signature for such a method yet, though, so it's currently lacking. Suggestions, as always, are very welcome.
&lt;/p&gt;

&lt;p&gt;
All the methods return the stub, so they can be chained, like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;sinon.stub(jQuery, &amp;quot;each&amp;quot;).callsArgWith(1, {}).returns({});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This stubs the 				&lt;code&gt;jQuery.each&lt;/code&gt; method. When called, it will call its second argument with an empty object and then returns an empty object.
&lt;/p&gt;

&lt;p&gt;
The real power in stubs is provided by the spy interface discussed previously. Remember that stubbed methods inherit the 				&lt;code&gt;restore&lt;/code&gt; method as well, to restore the original method.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_5&quot;&gt;Mocks&lt;/h2&gt;
&lt;p&gt;
			
									&lt;a href=&quot;http://xunitpatterns.com/Mock%20Object.html&quot;&gt;Mock objects&lt;/a&gt; are like both stubs and spies, and additionally have &lt;i&gt;pre-programmed behavior verification&lt;/i&gt; - so-called &lt;i&gt;expectations&lt;/i&gt; - built in. Mocks state their success criteria upfront, rather than the usual closing assertions, and fail immediately upon receiving unexpected calls. Finally, a call to 				&lt;code&gt;mock.verify()&lt;/code&gt; verifies that indeed all expectations are met.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80380_5_1&quot;&gt;Creating mocks&lt;/h3&gt;
&lt;p&gt;
To create mocks you can either create anonymous mock functions, like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test should call event handler&amp;quot;: function () {
  var mock = sinon.mock();
  var myElement = document.getElementsByTagName(&amp;quot;a&amp;quot;)[0];

  dom.addEventListener(myElement, &amp;quot;mouseover&amp;quot;, mock);
  dom.fireEvent(myElement, &amp;quot;mouseover&amp;quot;);

  mock.verify();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This test will fail immediately if the mock is called more than once, and the closing 				&lt;code&gt;verify()&lt;/code&gt; call will throw an exception if it wasn't called at least once.
&lt;/p&gt;

&lt;p&gt;
You can also mock methods on objects like we did we the spies and stubs before. The interface is slightly different because we need to create 1) a mock object and 2) expectations on the methods we want to test.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var mock = sinon.mock(jQuery);
mock.expects(&amp;quot;each&amp;quot;).once().callsArgWith(1, {}).returns({});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This creates an expectation that 				&lt;code&gt;jQuery.each&lt;/code&gt; is called once, and only once, and also instructs the mock to behave as the stub from before.
&lt;/p&gt;
	&lt;h3 id=&quot;toc80380_5_2&quot;&gt;Controlling mock expectations&lt;/h3&gt;
&lt;p&gt;
Sinon's mocks support both the spy and stub interfaces, although the spy interface isn't as interesting with mocks. Instead, you will typically use one of the following methods to state expectations upfront. Note that these also return the expectation, enabling you to chain them, resulting in good descriptions of the compound expectation.
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;
				&lt;code&gt;expectation.atLeast(callCount)&lt;/code&gt;&lt;br /&gt; Makes the mock accept any number of calls, so long as it is called at least the specified number of times.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.atMost(callCount)&lt;/code&gt;&lt;br /&gt; Makes the mock accept any number of calls, so long it is not called more than the specified number of calls.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.exactly(callCount)&lt;/code&gt;&lt;br /&gt; Specify the exact number of calls to satisfy the expectation.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.never()&lt;/code&gt;&lt;br /&gt; Shortcut for 				&lt;code&gt;exactly(0)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.once()&lt;/code&gt;&lt;br /&gt; Shortcut for 				&lt;code&gt;exactly(1)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.twice()&lt;/code&gt;&lt;br /&gt; Shortcut for 				&lt;code&gt;exactly(2)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.thrice()&lt;/code&gt;&lt;br /&gt; Shortcut for 				&lt;code&gt;exactly(3)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.withArgs(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Like the spy method 				&lt;code&gt;calledWith(arg1, arg2, ...)&lt;/code&gt;, only for upfront expectations.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.withExactArgs(arg1, arg2, ...)&lt;/code&gt;&lt;br /&gt; Like the spy method 				&lt;code&gt;calledWithExactly(arg1, arg2, ...)&lt;/code&gt;, only for upfront expectations.&lt;/li&gt;

&lt;li&gt;
				&lt;code&gt;expectation.on(thisObj)&lt;/code&gt;&lt;br /&gt; Expects the 				&lt;code&gt;this&lt;/code&gt; value of the call to match the specified object.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
Additionally, mocks inherit the 				&lt;code&gt;restore&lt;/code&gt; method, to restore the original method. However, in most cases you won't need it as 				&lt;code&gt;verify&lt;/code&gt; restores the method after verifying all expectations.
&lt;/p&gt;

&lt;p&gt;
The following is an example I used in the book. I built a 			
									&lt;a href=&quot;http://en.wikipedia.org/wiki/Comet_%28programming%29&quot;&gt;comet client&lt;/a&gt; that uses long polling to stream data from the server. The following test expects that calling the 				&lt;code&gt;connect&lt;/code&gt; method on the comet client in turn calls the 				&lt;code&gt;ajax.poll&lt;/code&gt; method with the specified url.
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;&amp;quot;test connect should start polling&amp;quot;: function () {
  var client = Object.create(ajax.cometClient);
  client.url = &amp;quot;/my/url&amp;quot;;
  var mock = sinon.mock(ajax);
  mock.expects(&amp;quot;poll&amp;quot;).once().withArgs(&amp;quot;/my/url&amp;quot;).returns({});

  client.connect();

  mock.verify();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
You will probably note that the 				&lt;code&gt;mock.verify()&lt;/code&gt; call towards the end there is the kind of scaffolding a good integration with the test framework can do away with, and I'd agree with you. I'll show what Sinon offers to in this area in the next post.
&lt;/p&gt;
	&lt;h2 id=&quot;toc80380_6&quot;&gt;Status&lt;/h2&gt;
&lt;p&gt;
Currently, everything showed in this post is functional, well tested and possible to use. If you want to try it, you can find a 			
									&lt;a href=&quot;http://cjohansen.no/sinon/sinon.preview-20100525.js&quot;&gt;preview version of Sinon here&lt;/a&gt;. Also, the 			
									&lt;a href=&quot;http://gitorious.org/sinon/&quot;&gt;full source is available on Gitorious&lt;/a&gt;. Documentation is sorely lacking, as the post you just read is currently all there is. There are more features ready for use as well, which will be covered in upcoming posts. Finally, I'm working on tools to test/stub/mock timers and XMLHttpRequest, but they're not done yet.
&lt;/p&gt;

&lt;p&gt;
Seeing as the interface is currently still being beaten into shape I hope some of you take the opportunity to tell me what's looking good, where the API fails, what's lacking, and other ideas/feedback you may have. Leave a comment, shoot me an 			
									&lt;a href=&quot;mailto:christian@cjohansen.no&quot;&gt;email at christian@cjohansen.no&lt;/a&gt; or holler at me on 			
									&lt;a href=&quot;http://twitter.com/cjno/&quot;&gt;Twitter (@cjno)&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>02 Apr 2010 12:25:52 GMT</pubDate>
  <title>Update on the node.js asserts</title>
  <link>http://www.cjohansen.no/en/node_js/update_on_the_node_js_asserts</link>
  <guid>http://www.cjohansen.no/en/node_js/update_on_the_node_js_asserts</guid>
  <comments>http://www.cjohansen.no/en/node_js/update_on_the_node_js_asserts#comments</comments>
  <description>
    
&lt;p&gt;
I realized that if you want the 			
									&lt;a href=&quot;http://gitorious.org/node-assert-extras&quot;&gt;assert-extras&lt;/a&gt; assertions, you probably want the built-in assertions as well.
&lt;/p&gt;

    
&lt;p&gt;
The repo is updated, and assert-extras now bundles the built-in asserts too, so you don't have to jump through the mixin hoop anytime you want to use it. Now you can simply do:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;var assert = require(&amp;quot;assert-extras&amp;quot;);
assert.ok(true);
assert.isFunction(function () {});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
			
									&lt;a href=&quot;http://gitorious.org/node-assert-extras&quot;&gt;Get it from Gitorious&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>01 Apr 2010 22:33:36 GMT</pubDate>
  <title>Unit testing node.js apps</title>
  <link>http://www.cjohansen.no/en/node_js/unit_testing_node_js_apps</link>
  <guid>http://www.cjohansen.no/en/node_js/unit_testing_node_js_apps</guid>
  <comments>http://www.cjohansen.no/en/node_js/unit_testing_node_js_apps#comments</comments>
  <description>
    
&lt;p&gt;
Recently I've been dabbling in the fantastic library that is 			
									&lt;a href=&quot;http://nodejs.org/&quot;&gt;node.js&lt;/a&gt;. Whenever I enter a new development environment I immediately poke around to figure out how to unit test things. I'm uncomfortable writing too much code without tests, especially when I'm on unfamiliar grounds. Here's what I landed on in round one.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc77303_1&quot;&gt;What node.js offers&lt;/h2&gt;
&lt;p&gt;
In case you haven't already checked it out, 			
									&lt;a href=&quot;http://nodejs.org&quot;&gt;node.js&lt;/a&gt; is &amp;quot;Evented I/O for 			
									&lt;a href=&quot;http://code.google.com/p/v8/&quot;&gt;V8 JavaScript&lt;/a&gt;&amp;quot; - a small framework for server-side JavaScript in a completely asynchronous fashion. node.js is already somewhat on par with 			
									&lt;a href=&quot;http://commonjs.org/&quot;&gt;CommonJS&lt;/a&gt;, implementing its 			
									&lt;a href=&quot;http://commonjs.org/specs/modules/1.0/&quot;&gt;Modules&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Node's focus is providing the low-level stuff, such as a file system module, TCP and HTTP modules and more. Relevant to testing, it also provides an 			
									&lt;a href=&quot;http://nodejs.org/api.html#_assert_module&quot;&gt;Assert module&lt;/a&gt;. The module is very low-level, it simply provides an 				&lt;code&gt;assert.fail&lt;/code&gt; method along with a few assertions:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;				&lt;code&gt;assert.ok(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.equal(actual, expected, message)&lt;/code&gt; - comparison by 				&lt;code&gt;==&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.notEqual(actual, expected, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.deepEqual(actual, expect, message)&lt;/code&gt; - recursive comparison&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.notDeepEqual(actual, expect, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.strictEqual(actual, expected, message)&lt;/code&gt; - comparison by 				&lt;code&gt;===&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.notStrictEqual(actual, expected, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.throws(block, error, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.doesNotThrow(block, error, message)&lt;/code&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
These are fine building blocks to build a test library on, but not exactly a whole lot to test an application with. For example, there is no test runner provided, so no structured output, no way to group tests and so on. I needed more.
&lt;/p&gt;
	&lt;h2 id=&quot;toc77303_2&quot;&gt;Nodeunit&lt;/h2&gt;
&lt;p&gt;
The 			
									&lt;a href=&quot;http://wiki.github.com/ry/node/&quot;&gt;node.js GitHub wiki&lt;/a&gt; has a 			
									&lt;a href=&quot;http://wiki.github.com/ry/node/modules&quot;&gt;list of modules&lt;/a&gt; which is very cool way to discover the world of node.js. I started perusing some of the alternatives on this page. Of the available testing tools, I guess 			
									&lt;a href=&quot;http://github.com/visionmedia/jspec&quot;&gt;JsSpec&lt;/a&gt;, which also works in browser, is one of the more accomplished ones, however I'm not too keen on the syntax.
&lt;/p&gt;

&lt;p&gt;
I landed on a small project called 			
									&lt;a href=&quot;http://github.com/caolan/nodeunit&quot;&gt;Nodeunit&lt;/a&gt;, which is mostly modeled after the 			
									&lt;a href=&quot;http://docs.jquery.com/QUnit&quot;&gt;QUnit&lt;/a&gt; API. It's very minimalistic, too minimalistic for my taste, but I liked its way of organizing stuff.
&lt;/p&gt;
	&lt;h3 id=&quot;toc77303_2_1&quot;&gt;How to use nodeunit&lt;/h3&gt;
&lt;p&gt;
In nodeunit, tests can simply be exported from modules. Every test method receives a test context object from nodeunit, which has the assertions and some state associated with the tests. Nodeunit is, as node.js itself, completely asynchronous. It simply assumes your tests will be asynchronous, and expects you to tell it when you're done running tests by calling the 				&lt;code&gt;done&lt;/code&gt; method on the test context object.
&lt;/p&gt;

&lt;p&gt;
The following is a slightly adjusted version of the example from nodeunit's GitHub repo:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;exports[&amp;quot;test some stuff&amp;quot;] = function(test){
    test.expect(1);
    test.ok(true, &amp;quot;this assertion should pass&amp;quot;);
    test.done();
};

exports[&amp;quot;test some other stuff&amp;quot;] = function(test){
    test.ok(false, &amp;quot;this assertion should fail&amp;quot;);
    test.done();
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Everything you need for testing inherently asynchronous code; a way to expect the number of asserts, and explicit test completion.
&lt;/p&gt;
	&lt;h3 id=&quot;toc77303_2_2&quot;&gt;Running tests&lt;/h3&gt;
&lt;p&gt;
One of the things that sold me on nodeunit was the very useful Readme Caolan provides with the code. He gives good pointers on how to run the tests, and suggests this script:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;#!/usr/local/bin/node

require.paths.push(__dirname);
require.paths.push(__dirname + '/deps');
require.paths.push(__dirname + '/lib');
var testrunner = require('nodeunit').testrunner;

process.chdir(__dirname);
testrunner.run(['test']);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Assuming you have dependencies in 				&lt;code&gt;deps&lt;/code&gt;, library code in 				&lt;code&gt;lib/&lt;/code&gt; and tests in 				&lt;code&gt;test&lt;/code&gt;, this will conveniently run all your tests. Save it in e.g. 				&lt;code&gt;run_tests&lt;/code&gt; and make the file executable and you're good to go.
&lt;/p&gt;
	&lt;h3 id=&quot;toc77303_2_3&quot;&gt;Autotesting&lt;/h3&gt;
&lt;p&gt;
I love automatically running tests. For client side JavaScript, I've been using my JstdUtil tool, and for Ruby I've been using Watchr for quite some time (actually jstd util uses Watchr under the hood as well). 			
									&lt;a href=&quot;http://github.com/mynyml/watchr&quot;&gt;Watchr&lt;/a&gt; can easily be used to run nodeunit tests automatically too. Save the following snippet in a file named 				&lt;code&gt;autotest.watchr&lt;/code&gt; in the root of your project:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def run_all_tests
  print `clear`
  puts &amp;quot;Tests run #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}&amp;quot;
  puts `./run_tests`
end

run_all_tests
watch(&amp;quot;(test|lib)(/.*)+.js&amp;quot;) { |m| run_all_tests }

@interrupted = false

# Ctrl-C
Signal.trap &amp;quot;INT&amp;quot; do
  if @interrupted
    abort(&amp;quot;\n&amp;quot;)
  else
    puts &amp;quot;Interrupt a second time to quit&amp;quot;
    @interrupted = true
    Kernel.sleep 1.5

    run_all_tests
    @interrupted = false
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The run it with 				&lt;code&gt;watchr autotest.watchr&lt;/code&gt;, and swoosh! Tests run automatically every time you save a file in the project. Now we're getting somewhere, but I still wanted more.
&lt;/p&gt;
	&lt;h2 id=&quot;toc77303_3&quot;&gt;Assertions&lt;/h2&gt;
&lt;p&gt;
I have previously implemented 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/source/browse/trunk/JsTestDriver/src/com/google/jstestdriver/javascript/Asserts.js&quot;&gt;a bunch of assertions&lt;/a&gt; for 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/&quot;&gt;JsTestDriver&lt;/a&gt;. I love high-level assertions, they make tests more concise, easier to read and less error-prone. So I went ahead and added the following 			
									&lt;a href=&quot;http://gitorious.org/node-assert-extras&quot;&gt;assertions for node.js&lt;/a&gt; as well:
&lt;/p&gt;

&lt;ul&gt;

&lt;li&gt;				&lt;code&gt;assert.isNull(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNotNull(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isTypeOf(value, type, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNotTypeOf(value, type, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isObject(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isFunction(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isString(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNumber(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isBoolean(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isUndefined(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNotUndefined(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isArray(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNaN(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNotNaN(value, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.match(value, pattern, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.noMatch(value, pattern, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isPrototypeOf(proto, object, message)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;				&lt;code&gt;assert.isNotPrototypeOf(proto, object, message)&lt;/code&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;
The assertions live in the 				&lt;code&gt;assert-extras&lt;/code&gt; modules, and you can use the with the regluar asserts like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;function mixin (target) {
    Array.prototype.slice.call(arguments, 1).forEach(function (object) {
        Object.keys(object).forEach(function (property) {
            target[property] = object[property];
        });
    });

    return target;
}

var assert = mixin({}, require(&amp;quot;assert&amp;quot;), require(&amp;quot;assert-extras&amp;quot;).assert);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now both the built-in assertions and the custom ones appear to live in the same module when using it.
&lt;/p&gt;
	&lt;h3 id=&quot;toc77303_3_1&quot;&gt;Test cases&lt;/h3&gt;
&lt;p&gt;
The last piece of the puzzle was a way to group tests in test cases. Caolan argues on nodeunit's GitHub repo that 				&lt;code&gt;setUp&lt;/code&gt; methods can be easily handled manually, and while that's true I think the proposed solution is less clear than desirable in a test case, so I wanted my regular 				&lt;code&gt;setUp&lt;/code&gt; and 				&lt;code&gt;tearDown&lt;/code&gt; methods. To scratch my own itch I 			
									&lt;a href=&quot;http://github.com/cjohansen/nodeunit&quot;&gt;forked nodeunit&lt;/a&gt; and added test cases. They can be used like so:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;testCase(exports, &amp;quot;some method&amp;quot;, {
    setUp: function () {
        this.someVal = 42;
    },

    tearDown: function () {
        // teardown code
    },

    &amp;quot;should do something&amp;quot;: function (test) {
        test.isFunction(some.method);
        test.equals(some.val, this.someVal);
        test.done();
    }
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
You can add several test cases with each their sets of 				&lt;code&gt;setUp&lt;/code&gt; and 				&lt;code&gt;tearDown&lt;/code&gt; methods in a module. The 				&lt;code&gt;testCase&lt;/code&gt; method is nothing fancy, it simply prepends the test case name to the names of all the tests, and takes care to run 				&lt;code&gt;setUp&lt;/code&gt; and 				&lt;code&gt;tearDown&lt;/code&gt; for all tests.
&lt;/p&gt;

&lt;p&gt;
That's what I have so far. Next up I imagine some way to more easily stub promises will be useful, but I need some more time developing and testing node applications before I know what I want.
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>08 Mar 2010 22:20:18 GMT</pubDate>
  <title>Test Driven JavaScript - The Book</title>
  <link>http://www.cjohansen.no/en/javascript/test_driven_javascript_the_book</link>
  <guid>http://www.cjohansen.no/en/javascript/test_driven_javascript_the_book</guid>
  <comments>http://www.cjohansen.no/en/javascript/test_driven_javascript_the_book#comments</comments>
  <description>
    
&lt;p&gt;
For those of you who didn't already know: I'm writing a book. It's about JavaScript, it's about unit testing and it's about Test Driven Development. It won't be out until October this year, but drafts are already available through Safari Rough Cut.
&lt;/p&gt;

    
&lt;p&gt;
I've been 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;tweeting tirelessly&lt;/a&gt; about writing this thing for quite some time, but as the Safari Rough Cuts program opened today I felt it suitable to give some more tangible information about it.
&lt;/p&gt;
	&lt;h2 id=&quot;toc76681_1&quot;&gt;What's it about?&lt;/h2&gt;
&lt;p&gt;
The book - tentatively entitled &amp;quot;Test Driven JavaScript Development&amp;quot; - is basically about test driven development and JavaScript. It's a subject that has interested me for some time. Test driven development (or behavior driven, if that's your cup) has made my life as a programmer so much easier - no longer do I need to worry about getting all the details right a one time, no longer do I need to plan out an entire interface prior to implementing it in order to produce a reasonable elegant result.
&lt;/p&gt;

&lt;p&gt;
The book teaches unit testing and test driven development in the setting of JavaScript. But there's more - it also teaches JavaScript in the setting of test driven development. The intended audience is both JavaScripters looking for more sustainable development methodologies as well as programmers used to testing but unfamiliar with JavaScript.
&lt;/p&gt;
	&lt;h2 id=&quot;toc76681_2&quot;&gt;What's inside?&lt;/h2&gt;
&lt;p&gt;
The book has four parts, and anyone of them can be read in isolation, depending on prior experience.
&lt;/p&gt;
	&lt;h3 id=&quot;toc76681_2_1&quot;&gt;Automated testing&lt;/h3&gt;
&lt;p&gt;
The first part deals with automated testing, introduces asserts, unit tests and the test driven development methodology. It's slightly theoretical, but uses loads of examples and provides a good background for the later parts.
&lt;/p&gt;
	&lt;h3 id=&quot;toc76681_2_2&quot;&gt;JavaScript for programmers&lt;/h3&gt;
&lt;p&gt;
The second part is entitled &amp;quot;JavaScript for programmers&amp;quot;, and hopefully, is just that. It gives a tour of the features that sets JavaScript apart from other languages. It's no beginners introduction to JavaScript, but instead assumes the reader knows how to program and deals with some of the finer details of the JavaScript language, such as its functions, prototypal inheritance and the object model in general. The second part also covers unobtrusive JavaScript and feature testing, important topics for applications aimed for the general web.
&lt;/p&gt;
	&lt;h3 id=&quot;toc76681_2_3&quot;&gt;Real world test driven JavaScript&lt;/h3&gt;
&lt;p&gt;
The third part of the book is the biggest one, and shows five &amp;quot;real world&amp;quot; examples of test driving JavaScript development. I've tried to make the examples as relevant and non-fictional as possible. These chapters work through five small projects in great detail. Test by test, line by line of production code, simple interfaces are built, refactored and explained. The quotes imply that there simply isn't room in a book to cover too big projects in such detail, and in order to get a wide range of topics, I've had to simplify some of these from what they would have looked like in &amp;quot;the real world&amp;quot;.
&lt;/p&gt;

&lt;p&gt;
The topic of these examples ranges from the observer pattern, an &amp;quot;Ajax&amp;quot; implementation, Comet, node.js and finally DOM scripting. They focus mainly on the testing and the process of using tests to design interfaces, refactor heavily and other concepts such as stubbing and mocking.
&lt;/p&gt;
	&lt;h3 id=&quot;toc76681_2_4&quot;&gt;Testing patterns and best practices&lt;/h3&gt;
&lt;p&gt;
The final part of the book sums up some lessons learned through the above examples from part 3 and dives deeper into some concepts such as stubbing and mocking, which are important topics to cover in order to write truly isolated unit tests.
&lt;/p&gt;
	&lt;h2 id=&quot;toc76681_3&quot;&gt;On writing a book&lt;/h2&gt;
&lt;p&gt;
The book is being published through Addison-Wesley Professional, and as such I am surrounded by a very smooth and professional machinery. I have to say, the writing process has been very pleasant, and I have a very nice editor and staff working on the book. AW provides a team of reviewers, and boy are these guys (and gal) great. They help out by finding everything from typos and questionable formulations to bad ideas that are hard to discover when you've got your nose deep into the material. I'm very lucky to have been able to do this.
&lt;/p&gt;
	&lt;h3 id=&quot;toc76681_3_1&quot;&gt;Safari Rough Cuts&lt;/h3&gt;
&lt;p&gt;
As I mentioned in the introduction, what prompted this announcement was the availability of the 			
									&lt;a href=&quot;http://my.safaribooksonline.com/9780321684097&quot;&gt;Safari Rough Cuts&lt;/a&gt; program for the book. Safari Rough Cuts is like &amp;quot;beta&amp;quot; for books. The three first chapters have just been made available in very early draft form, and anyone with a Safari account can read them and provide feedback right this instance. If you are on Safari I hope you want to stop by, 			
									&lt;a href=&quot;http://my.safaribooksonline.com/9780321684097&quot;&gt;read the chapters&lt;/a&gt; and provide some feedback. It will surely help the book get better!
&lt;/p&gt;

&lt;p&gt;
As for those of you without an account, you can either get one, or wait. In any case, chapter 3 is freely available to anyone. It's the tools chapter, which covers quite a few tools, but focuses mainly on 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/&quot;&gt;JsTestDriver&lt;/a&gt; which was chosen as the main tool for many of the examples.
&lt;/p&gt;

&lt;p&gt;
If you're on Twitter, you'll find me as 			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;@cjno&lt;/a&gt;, do stop by!
&lt;/p&gt;

&lt;p&gt;
Side note: This post was written to the sound of 			
									&lt;a href=&quot;http://open.spotify.com/album/0F91PqtAxUbUlKOivIDAMH&quot;&gt;Snakes for the Divine&lt;/a&gt;, High on Fire's new album. It ain't Blessed Black Wings, and it ain't Death is this Communion, but it sure is a cool album. Check it out!
&lt;/p&gt;

&lt;p&gt;
Hope as many as possible of you check it out and if you do, please tell me what you think!
&lt;/p&gt;

  </description>
</item>
            <item>
  <pubDate>04 Nov 2009 23:38:00 GMT</pubDate>
  <title>Jstdutil - A Ruby wrapper over JsTestDriver</title>
  <link>http://www.cjohansen.no/en/javascript/jstdutil_a_ruby_wrapper_over_jstestdriver</link>
  <guid>http://www.cjohansen.no/en/javascript/jstdutil_a_ruby_wrapper_over_jstestdriver</guid>
  <comments>http://www.cjohansen.no/en/javascript/jstdutil_a_ruby_wrapper_over_jstestdriver#comments</comments>
  <description>
    
&lt;p&gt;
Today I needed remote access to a gem I've been tinkering with for a while, so I pushed it to 			
									&lt;a href=&quot;http://gemcutter.org&quot;&gt;Gemcutter&lt;/a&gt;. It's called 			
									&lt;a href=&quot;http://gitorious.org/jstestdriver-utilities/jstdutil&quot;&gt;jstdutil&lt;/a&gt;, and it provides a small Ruby wrapper over 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/&quot;&gt;JsTestDriver&lt;/a&gt; that adds colored output, a short, snappy 				&lt;code&gt;`jstestdriver`&lt;/code&gt; command and autotest.
&lt;/p&gt;

    	&lt;h2 id=&quot;toc68625_1&quot;&gt;Install it&lt;/h2&gt;
&lt;p&gt;
The gem is available on 			
									&lt;a href=&quot;http://gemcutter.org&quot;&gt;Gemcutter&lt;/a&gt;, which requires that you install their gem (and use RubyGems &amp;gt;= 1.3.5):
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;gem update --system
gem install gemcutter
gem tumble&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then you're ready to install:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;gem install jstdutil&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then 			
									&lt;a href=&quot;http://code.google.com/p/js-test-driver/downloads/list&quot;&gt;download the JsTestDriver jar&lt;/a&gt;. Put it somewhere safe, like 				&lt;code&gt;~/bin/java&lt;/code&gt;, and set the environment variable 				&lt;code&gt;$JSTESTDRIVER_HOME&lt;/code&gt; to the directory where you put the file (e.g., 				&lt;code&gt;export JSTESTDRIVER_HOME=~/bin/java&lt;/code&gt;). That's it!
&lt;/p&gt;
	&lt;h2 id=&quot;toc68625_2&quot;&gt;Use it&lt;/h2&gt;
&lt;p&gt;
Now you can run JsTestDriver with 				&lt;code&gt;`jstestdriver`&lt;/code&gt;. For instance, to start the server, you can issue:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;jstestdriver --port 4224&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then, run all your tests:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;jstestdriver --tests all
# If config is not in cwd:
jstestdriver --config path/to/config.conf --tests all&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The output should be nicely colored, even on Windows. If you're not seeing colors on Windows, you need to:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;gem install win32console&lt;/code&gt;&lt;/pre&gt;
	&lt;h3 id=&quot;toc68625_2_1&quot;&gt;Autotest&lt;/h3&gt;
&lt;p&gt;
The best part is autotest. Simply:
&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;bat&quot;&gt;jsautotest
# If config is not in cwd:
jsautotest --config path/to/config.conf&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Swish! Autotest runs the entire test suite initially, and then waits for any of your files to change. Once a file changes, jstdutil makes some intelligent guesses on which test cases were affected, and runs only the corresponding tests. If you want to rerun the test suite, simply issue 				&lt;code&gt;Ctrl-C&lt;/code&gt; in the shell where autotest is running. Quickly issuing 				&lt;code&gt;Ctrl-C&lt;/code&gt; twice aborts autotest.
&lt;/p&gt;
	&lt;h2 id=&quot;toc68625_3&quot;&gt;A word of warning&lt;/h2&gt;
&lt;p&gt;
As I mentioned, I pushed the gem in need of remote access earlier today. This means that it''s not quite as finished as I had planned, but I've been using it for a few weeks, and it does work great most of the time. If you encounter any issues, please do let me know. Even better: 			
									&lt;a href=&quot;http://gitorious.org/jstestdriver-utilities/jstdutil&quot;&gt;clone the project on Gitorious&lt;/a&gt;, or 			
									&lt;a href=&quot;http://github.com/cjohansen/jstdutil&quot;&gt;fork it on GitHub&lt;/a&gt; and fix it yourself.
&lt;/p&gt;
	&lt;h2 id=&quot;toc68625_4&quot;&gt;Why write a wrapper?&lt;/h2&gt;
&lt;p&gt;
These features could probably easily have been added to the JsTestDriver project itself. In fact, the right thing for me to do would probably be to submit a patch of sorts. However, I enjoy Ruby alot more than Java, and my Java is a bit rusty. I hope JsTestDriver one day incorporates something like this, lessening the burden of installing it (if you're really into colored output and shell autotest like me).
&lt;/p&gt;

&lt;p&gt;
Happy testing, and please to report back any troubles you may encounter!
&lt;/p&gt;

&lt;p&gt;
			
									&lt;a href=&quot;http://twitter.com/cjno&quot;&gt;Follow me on Twitter&lt;/a&gt;.
&lt;/p&gt;

  </description>
</item>
      </channel>
</rss>

