JavaScript Unit Testing Part 1: JsUnit

In this post we will examine the 1st of 4 JavaScript Unit Testing frameworks... JsUnit.

<p>In subsequent posts we will cover <a target="_blank" href="http://jania.pe.kr/aw/moin.cgi/JSSpec">JSSpec</a>, <a target="_blank" href="http://docs.jquery.com/QUnit">QUnit</a>, and <a target="_blank" href="http://developer.yahoo.com/yui/yuitest/">YUI Test</a>.</p>    <p>First of all, lets define some JavaScript code that we want to Unit Test. I wrote the following Pig Latin JavaScript utility for the sole purpose of this Unit Testing seriesโ€ฆ </p> <p>*Note: I am aware the code needs to be refactored. We will address that in a future blog post :)ย  </p>    <pre><br>/*const*/ var CONSONANTS = 'bcdfghjklmnpqrstvwxyz';<br>/*const*/ var VOWELS = 'aeiou';<br><br>function EnglishToPigLatin(english) {<br>   /*const*/ var SYLLABLE = 'ay';<br><br>   var pigLatin = '';<br><br>   if (english != null && english.length > 0 && <br>      (VOWELS.indexOf(english[0]) > -1 || CONSONANTS.indexOf(english[0]) > -1 )) {<br>      if (VOWELS.indexOf(english[0]) > -1) {<br>         pigLatin = english + SYLLABLE;<br>      } else {      <br>         var preConsonants = '';<br>         for (var i = 0; i < english.length; ++i) {<br>            if (CONSONANTS.indexOf(english[i]) > -1) {<br>               preConsonants += english[i];<br>               if (preConsonants == 'q' && i+1 < english.length && english[i+1] == 'u') {<br>                  preConsonants += 'u';<br>                  i += 2;<br>                  break;<br>               }<br>            } else {<br>               break;<br>            }<br>         }<br>         pigLatin = english.substring(i) + preConsonants + SYLLABLE;<br>      }<br>   }<br><br>   return pigLatin;<br>}</pre> <p>Next we need to define a set of Unit Tests using JsUnit. I am using JsUnit 2.2 Alpha 11 for this example.</p> <p>In order to create the Unit Tests we need to know the business rules for the Pig Latin methodโ€ฆ </p> <ol><li>In words that begin with <a href="http://en.wikipedia.org/wiki/Consonant">consonant</a> sounds, the initial consonant or <a href="http://en.wikipedia.org/wiki/Consonant_cluster">consonant cluster</a> or diagraph is moved to the end of the word, and "ay" is addedโ€ฆ</li>   <li>In words that begin with <a href="http://en.wikipedia.org/wiki/Vowel">vowel</a> sounds or <a href="http://en.wikipedia.org/wiki/Silent_letter">silent consonants</a>, the syllable "ay" is added to the end of the word. In some dialects, to aid in pronunciation, an extra consonant is added to the beginning of the suffix.</li></ol><p>Now that we know the rules, lets start making some Unit Testsโ€ฆ</p> <pre><html><br> <head><br>   <title>Test Page for EnglishToPigLatin(english)</title><br>   <link rel="stylesheet" type="text/css" href="../css/jsUnitStyle.css"><br>   <script language="JavaScript" type="text/javascript" src="../app/jsUnitCore.js"></script><br>   <script language="JavaScript" type="text/javascript" src="./PigLatin.js"></script><br> </head><br> <body><br>  <script language="javascript"><br>   function testPassingNullShouldReturnBlank() {<br>      assertEquals('null returns a blank', '', EnglishToPigLatin(null));<br>   }<br><br>   function testPassingBlankShouldReturnBlank() {<br>      assertEquals('blank returns a blank', '', EnglishToPigLatin(''));<br>   }<br><br>   function testConsonantBeastShouldReturnEastbay() {<br>      assertEquals('beast returns eastbay', 'eastbay', EnglishToPigLatin('beast'));<br>   }   <br><br>   function testConsonantDoughShouldreturnOughday() {<br>      assertEquals("dough returns oughday", 'oughday', EnglishToPigLatin('dough'));<br>   }<br><br>   function testConsonantHappyShouldReturnAppyhay() {<br>      assertEquals("happy returns appyhay", 'appyhay', EnglishToPigLatin('happy'));<br>   }        <br><br>   function testConsonantsQuestionShouldReturnEstionquay() {<br>      assertEquals("question returns estionquay", 'estionquay', EnglishToPigLatin('question'));<br>   }<br><br>   function testConsonantsStarShouldReturnArstay() {<br>      assertEquals("star returns arstay", 'arstay', EnglishToPigLatin('star'));<br>   } <br><br>   function testConsonantsThreeShouldReturnEethray() {<br>      assertEquals("three returns eethray", 'eethray', EnglishToPigLatin('three'));<br>   }<br><br>   function testVowelAppleShouldReturnAppleay() {<br>      assertEquals("apple returns appleay", 'appleay', EnglishToPigLatin('apple'));<br>   }<br><br>   function testVowelElijahShouldReturnElijahay() {<br>      assertEquals("elijah returns elijahay", 'elijahay', EnglishToPigLatin('elijah'));<br>   }<br><br>   function testVowelIglooShouldReturnIglooay() {<br>      assertEquals("igloo returns iglooay", 'iglooay', EnglishToPigLatin('igloo'));<br>   }<br><br>   function testVowelOctopusShouldReturnOctopusay() {<br>      assertEquals("octopus returns octopusay", 'octopusay', EnglishToPigLatin('octopus'));<br>   }<br><br>   function testVowelUmbrellaShouldReturnUmbrellaay() {<br>      assertEquals("umbrella returns umbrellaay", 'umbrellaay', EnglishToPigLatin('umbrella'));<br>   }<br><br>   function testPassingNumberShouldReturnBlank() {<br>      assertEquals("1234567890 returns blank", '', EnglishToPigLatin('1234567890'));<br>   }<br><br>   function testPassingSymbolsShouldReturnBlank() {<br>      assertEquals("~!@#$%^&*()_+ returns blank", '', EnglishToPigLatin('~!@#$%^&*()_+'));<br>   }<br>    </script><br> </body><br></html><br></pre> <p>There are several different types of asserts that JsUnit supports...</p><ol><li>assert([comment], booleanValue)</li>   <li>assertTrue([comment], booleanValue)</li>   <li>assertFalse([comment], booleanValue)</li>   <li>assertEquals([comment], value1, value2)</li>   <li>assertNotEquals([comment], value1, value2)</li>   <li>assertNull([comment], value)</li>   <li>assertNotNull([comment], value)</li>   <li>assertUndefined([comment], value)</li>   <li>assertNotUndefined([comment], value)</li>   <li>assertNaN([comment], value)</li>   <li>assertNotNaN([comment], value)</li>   <li>fail(comment)</li></ol><p>JsUnit has a testRunner to execute all of your Unit Tests. If all is well, your status bar will be green. If any asserts failed, they will be displayed in a list control where any assert comment can be retrieved</p> <a href="http://lh3.ggpht.com/_L6DiZQsfJzs/SdrV0Axc9bI/AAAAAAAAGw0/PH8z74w0rag/s1600-h/testRunner%5B3%5D.png"><img title="testRunner" border="0" alt="testRunner" src="http://lh6.ggpht.com/_L6DiZQsfJzs/SdrV4U9-qbI/AAAAAAAAGw4/4NaS4uIHNEs/testRunner_thumb%5B1%5D.png?imgmax=800" width="404" height="242"></a> <p>Overall, JsUnit is a decent Unit Testing framework for JavaScript. You can also bundle tests into suites and run multiple suites. As most testing frameworks, you can also use setUp() and tearDown() methods to prepare the environment for each test method. </p>

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit