<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Platformability &#187; Mock4JS</title>
	<atom:link href="http://blog.caplin.com/tag/mock4js/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.caplin.com</link>
	<description>SWIMMING WITH TECHNOLOGY</description>
	<lastBuildDate>Thu, 09 Sep 2010 09:20:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Pitfalls of Exception expectations in JsUnit</title>
		<link>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/</link>
		<comments>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 12:00:25 +0000</pubDate>
		<dc:creator>Ian Alderson</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JsCoverage]]></category>
		<category><![CDATA[Mock4JS]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1084</guid>
		<description><![CDATA[At Caplin we use the JsUnit framework to test our JavaScript code. Over time we have made minor modifications to it, integrating Mock4JS and JSCoverage, as well as adding a few of our own extensions that are sympathetic to our JavaScript coding style, however, by and large, our tests are written using plain old JsUnit [...]]]></description>
			<content:encoded><![CDATA[<p>At Caplin we use the <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qc3VuaXQubmV0Lw==">JsUnit</a> framework to test our JavaScript code. Over time we have made minor modifications to it, integrating  <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2s0anMuc291cmNlZm9yZ2UubmV0Lw==">Mock4JS</a> and <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NpbGljb25mb3Jrcy5jb20vanNjb3ZlcmFnZS8=">JSCoverage</a>, as well as adding a few of our own extensions that are sympathetic to our JavaScript coding style, however, by and large, our tests are written using plain old JsUnit assertions.</p>
<p>One of the main reasons we were keen to adopt JsUnit five years ago was its similarity to <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qdW5pdC5vcmcv">JUnit 3</a>. Back then our developers had been using JUnit for a few years, and familiarity of the JsUnit API meant that we could immediately start writing tests. Unfortunately the old adage &#8220;familiarity breeds contempt&#8221; reared its ugly head, and we discovered that our main issue with JsUnit were the occasional, very subtle, differences between it and JUnit. The logic for a test that works in JUnit might not work in JsUnit.<br />
<span id="more-1084"></span><br />
An example of this is highlighted by the test that would be written for the example <code>JobQueue</code> class defined below. Its purpose is to queue JavaScript functions for invocation at some point in the future. The <code>addJob()</code> method employs the <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9GYWlsLWZhc3Q=">fast-fail</a> philosophy to throw an exception if the <code>fJobToExecuteLater</code> argument is <code>null</code> or <code>undefined</code>, rather than fail later on when an attempt is made to execute it.</p>
<pre class="brush: jscript;">
function JobQueue()
{
   this.m_pQueue = [];
}

JobQueue.prototype.addJob = function(fJobToExecuteLater)
{
   if (fJobToExecuteLater == null) // this is true if it is undefined
   {
      throw new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;);
   }
   this.m_pQueue.push(fJobToExecuteLater);
};

// other methods...
</pre>
<p>The JsUnit test written to verify the behaviour would look something like:</p>
<pre class="brush: jscript;">
var g_oJobQueue = null;

function setUp()
{
   g_oJobQueue= new JobQueue();
}

function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   try
   {
      g_oJobQueue.addJob(null);
      fail(&quot;Unexpected success invoking addJob() with null job&quot;);
   }
   catch (e)
   {
      // expected exception
   }
}
</pre>
<p>Casting a casual (JUnit 3) glance over this test, everything looks to be in order. The test checks that an exception is thrown if the <code>addJob()</code> method is passed a <code>null</code> argument and remembers to invoke <code>fail()</code> if the exception isn&#8217;t thrown. This latter point is important since if it is omitted then the test will pass regardless of whether an exception is thrown or not.</p>
<p>The equivalent test in Java would work without any problems, however in JavaScript there is a hidden bug within this test logic. Within JUnit the <code>fail()</code> method throws a subclass of <code>Error</code>, which <strong>won’t</strong> be caught by a catch block expecting an Exception. Unfortunately JavaScript has no such distinctions between errors and exceptions, and the call to <code>fail()</code> throws an exception which <strong>will</strong> be caught within the catch block.</p>
<p><strong>Solutions to the Exception expection issue</strong></p>
<p>There are two approaches that we have taken to resolving this issue.</p>
<p><strong>1.</strong> We extended the JsUnit API to add a new assertion method, <code>assertFails()</code>, that encapsulates the logic necessary to ensure that an exception is thrown, and fail if it hasn&#8217;t. It takes three arguments:</p>
<p>&nbsp;&nbsp;&nbsp;<strong>i.</strong> A comment to output if the test fails<br />
&nbsp;&nbsp;&nbsp;<strong>ii.</strong> A reference to the function to invoke which is expected to throw an exception, if this doesn&#8217;t throw an exception then the assertion fails<br />
&nbsp;&nbsp;&nbsp;<strong>iii.</strong> The exception that is expected to be thrown (optional, if omitted the assertion just ensures that an exception is thrown)</p>
<p>Using the <code>addJob()</code> test can be rewritten to use <code>assertFails()</code>:</p>
<pre class="brush: jscript;">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   assertFails(&quot;Unexpected success invoking addJob() with null job&quot;,
                   function() {
                      g_oJobQueue.addJob(null);
                   });
}
</pre>
<p><strong>2.</strong> We verify that the exception that is thrown is the one that we expect. This particular approach has been met with trepidation from some of our developers who are concerned that verification of exceptions will lead to fragile test code, prone to break if someone changes the text within an exception (presumably to make it more helpful). There are certainly pros and cons to this, however in my experience it is rare that changes are made to the descriptions passed into the exceptions thrown by our code, and the overhead of these verifications is negligible.</p>
<p>The original test code can be rewritten to assert that the exception is the expected one:</p>
<pre class="brush: jscript;">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   try
   {
      g_oJobQueue.addJob(null);
      fail(&quot;Unexpected success invoking addJob() with null job&quot;);
   }
   catch (e)
   {
      var oExpectedException =
               new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;);
      assertEquals(oExpectedException.toString(), e.toString());
   }
}
</pre>
<p>Alternatively <code>assertFails()</code> can be used as such:</p>
<pre class="brush: jscript;">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   assertFails(&quot;Unexpected success invoking addJob() with null job&quot;,
                   function() {
                      g_oJobQueue.addJob(null);
                   },
                   new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;));
}
</pre>
<p><strong>Conclusion</strong></p>
<p>This article is not intended to be a criticism of JsUnit. The issue highlighted here is simply due to a difference between the JavaScript and Java languages with respect to their exception handling which led to some tests being marked as successful when they shouldn&#8217;t. Over the last five years I have found that JsUnit has been reliable unit testing framework and, combined with Mock4JS and a TDD philosophy, it can form the solid foundations from which enterprise level JavaScript APIs and applications can be built.</p>
<p>Since we made our decision to use JsUnit we have never really looked back. So far it has managed to do everything that we have needed from it. However if you are looking into unit testing your JavaScript, then <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9MaXN0X29mX3VuaXRfdGVzdGluZ19mcmFtZXdvcmtzI0phdmFTY3JpcHQ=">this list of JavaScript unit testing frameworks</a> should be a good starting point to uncover one that is suitable for you. Just remember, it doesn&#8217;t matter which framework you choose, you need to be aware of the subtle nuisances of JavaScript, compared to any other languages you might be familiar with, to avoid the sort of trap that we fell into.</p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1084" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to dynamically create a class definition for use with Mock4JS</title>
		<link>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/</link>
		<comments>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 17:00:28 +0000</pubDate>
		<dc:creator>Phil Leggetter</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Ajax Testing]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mock4JS]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=187</guid>
		<description><![CDATA[Mock4JS is a really useful unit testing helper library that allows you to create mocks of your JavaScript classes. What it doesn&#8217;t presently support is mocking of objects that you can&#8217;t create an instance of yourself using new Class() or of objects that are dynamically created and have functions appended to them. What do I [...]]]></description>
			<content:encoded><![CDATA[<p><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2s0anMuc291cmNlZm9yZ2UubmV0Lw==">Mock4JS</a> is a really useful unit testing helper library that allows you to create mocks of your JavaScript classes. What it doesn&#8217;t presently support is mocking of objects that you can&#8217;t create an instance of yourself using <code>new Class()</code> or of objects that are dynamically created and have functions appended to them.</p>
<p><span id="more-187"></span></p>
<h3>What do I mean by not being able to &#8220;create an instance of yourself using <code>new Class()</code>&#8220;?</h3>
<pre class="javascript" name="code">MyClassDefinition = function()
{
};

MyClassDefintion.prototype.myFunction = function()
{
    // do some stuff
};
MyClassDefinition = new MyClassDefinition();</pre>
<p>Here we lose the ability to do <code>new MyClassDefinition();</code></p>
<h3>What do I mean by &#8220;objects that are dynamically created&#8221;?</h3>
<pre class="javascript" name="code">// create an object using the object literal notation
var oObj = {};

// dynamically append a function
oObj.myFunction = function()
{
    // do some stuff
};</pre>
<p>Code written in both these ways make it more difficult to create a mock using Mock4JS because it expects a function reference to be passed to the mock method call.</p>
<p>A way around this is to dynamically create a definition from the object. This is done using the following piece of code:</p>
<pre class="javascript" name="code">function createMockDefinition(oObject)
{
    var oMockedDefinition = new Function();
    for( var x in oObject )
    {
        // Only add functions to the dynamically created prototype
        if( typeof oObject[ x ] == "function" )
        {
            oMockedDefinition.prototype[x] = function(){};
        }
    }
    return oMockedDefinition;
};</pre>
<p>With the above code we have now created a class definition that we can pass to the Mock4JS <code>mock()</code> function.</p>
<pre class="javascript" name="code">function myTest()
{
    var oObjectIWantToTest = {};
    oObjectIWantToTest.functionIWantToTest = function(){};

    var oMyMockDefinition = createMockDefinition( oObjectIWantToTest );
    var oMyMock = mock( oMyMockDefinition );
    var oMyMockProxy = oMyMock.proxy();

    // setup expectations
    oMyMock.expects(once()).functionIWantToTest("myArgument");

    // call function and execute mock method.
    oMyMockProxy.functionIWantToTest("myArgument");

    // Finally, verify the expected mock methods have been called.
    // If not, an exception will be thrown.
    Mock4JS.verifyAllMocks();
};</pre>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=187" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
