Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Remember what the point of unit-testing is: to ensure a particular module of code reacts to some stimuli in an expected manner. In JS, a significant portion of your code, (unless you have some lifecycle framework like Sencha or YUI) will either be directly manipulating the DOM or making remote calls. To test these things, you simply apply traditional unit-testing techniques of dependency injection and mocking/stubbing. That means you must write each function, or class, that you want to unit-test to accept mocks of the dependent structures. </p> <p>jQuery supports this by allowing you to pass an XML document into all traversal functions. Whereas you might normally write</p> <pre><code>$(function() { $('.bright').css('color','yellow'); } </code></pre> <p>you'll instead want to write</p> <pre><code>function processBright(scope) { // jQuery will do the following line automatically, but for sake of clarity: scope = scope || window.document; $('.bright',scope).css('color','yellow'); } $(processBright); </code></pre> <p>Notice we not only pull the logic out of the anonymous function and give it a name, we also make that function accept a scope parameter. When that value is null, the jQuery calls will still function as normal. However, we now have a vector for injecting a mock document that we can inspect after the function is invoked. The unit-test could look like</p> <pre><code>function shouldSetColorYellowIfClassBright() { // arrange var testDoc = $('&lt;html&gt;&lt;body&gt;&lt;span id="a" class="bright"&gt;test&lt;/span&gt;&lt;/body&gt;&lt;/html&gt;'); // act processBright(testDoc); // assert if (testDoc.find('#a').css('color') != 'bright') throw TestFailed("Color property was not changed correctly."); } </code></pre> <p>TestFailed could look like this:</p> <pre><code>function TestFailed(message) { this.message = message; this.name = "TestFailed"; } </code></pre> <p>The situation is similar with remote calls, though rather than actually injecting some facility, you could get away with a masking stub. Say you have this function:</p> <pre><code>function makeRemoteCall(data, callback) { if (data.property == 'ok') $.getJSON({url:'/someResource.json',callback:callback}); } </code></pre> <p>You would test it as such:</p> <pre><code>// test suite setup var getJSON = $.getJSON; var stubCalls = []; $.getJSON = function(args) { stubCalls[stubCalls.length] = args.url; } // unit test 1 function shouldMakeRemoteCallWithOkProperty() { // arrange var arg = { property: 'ok' }; // act makeRemoteCall(arg); // assert if (stubCalls.length != 1 || stubCalls[0] != '/someResource.json') throw TestFailed("someResource.json was not requested once and only once."); } // unit test 2 function shouldNotMakeRemoteCallWithoutOkProperty() { // arrange var arg = { property: 'foobar' }; // act makeRemoteCall(arg); // assert if (stubCalls.length != 0) throw TestFailed(stubCalls[0] + " was called unexpectedly."); } // test suite teardown $.getJSON = getJSON; </code></pre> <p>(You can wrap that whole thing in the <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth" rel="noreferrer">module pattern</a> to not litter the global namespace.)</p> <p>To apply all of this in a test-driven manner, you would simply write these tests first. This is a straightforward, no frills, and most importantly, effective way of unit-testing JS.</p> <p>Frameworks like qUnit can be used to drive your unit-tests, but that is only a small part of the problem. Your code must be written in a test-friendly way. Also, frameworks like Selenium, HtmlUnit, jsTestDriver or Watir/N are for integration testing, not for unit-testing per se. Lastly, by no means must your code be object-oriented. The principles of unit-testing are easily confused with the practical application of unit-testing in object-oriented systems. They are separate but compatible ideas.</p> <p><strong>Testing Styles</strong></p> <p>I should note that two different testing styles are demonstrated here. The first assumes complete ignorance of the implementation of processBright. It could be using jQuery to add the color style, or it could be doing native DOM manipulation. I'm merely testing that the <em>external behavior of the function is as expected</em>. In the second, I assume knowledge of an internal dependency of the function (namely $.getJSON), and those tests cover <em>the correct interaction with that dependency</em>.</p> <p>The approach you take depends on your testing philosophy and overall priorities and cost-benefit profile of your situation. The first test is relatively pure. The second test is simple but relatively fragile; if I change the implementation of makeRemoteCall, the test will break. Preferably, the assumption that makeRemoteCall uses $.getJSON is at least justified by the documentation of makeRemoteCall. There are a couple more disciplined approaches, but one cost-effective approach is to wrap dependencies in wrapper functions. The codebase would depend only on these wrappers, whose implementations can be easily replaced with test stubs at test-time.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload