Saturday, February 13, 2016

Unit Testing Plain Old JavaScript (Part 1)

I've written about unit testing quite a bit, with a focus on Jasmine (for Angular) and NUnit (for .NET).  Lately I've been interested in improving my skills as a front-end developer so I started thinking about writing a simple HTML5 based Hangman game for my kids to use to practice their vocabulary.  One thing led to another and I ended up deciding that I wanted to do the whole thing as simply as possible with a full complement of unit tests.  Well, to do that I need to be able to unit test plain old JavaScript, and here we are.

The first thing to do is download the Jasmine framework.  I've created a folder on my desktop called Hangman to hold everything.  So I went here and downloaded the latest version of Jasmine (2.4.1 as of this writing).  I extracted the files from the /lib/jasmine-2.4.1 folder into a /lib folder in my Hangman folder.  You can technically get by with just jasmine.js, jasmine.html.js, and boot.js, but I use all the files because the styling is nice and they're already done anyway so it doesn't hurt.

Really briefly, jasmine.js contains the actual jasmine testing framework.  jasmine-html.js contains functions that help format the page (and do some other things that you can see for yourself if you look at the file).  boot.js initializes jasmine.

Now we need code to test.  In my Hangman folder I have a folder called src and a folder called spec.  In the src folder I have a single file: hangman.js.  In the spec folder I have a single file: hangman.js (I usually prefer to name my spec files with either a .test.js or .spec.js suffix, but I didn't this time).  Since I'm using test-driven development neither file contains anything right now.

The last piece is SpecRunner.html.  This is the file that you'll open to run your tests.  In order to run your tests, this file will need to know where your tests and your code are.  So the contents of SpecRunner.html look pretty much like this:

<html>
<head>
  <title>Jasmine Spec Runner v2.4.1</title>

  <link href="lib/jasmine_favicon.png" rel="shortcut icon" type="image/png"></link>
  <link href="lib/jasmine.css" rel="stylesheet"></link>

  <script src="lib/jasmine.js"></script>
  <script src="lib/jasmine-html.js"></script>
  <script src="lib/boot.js"></script>

  <!-- include source files here... -->
  <script src="src/hangman.js"></script>

  <!-- include spec files here... -->
  <script src="spec/hangman.js"></script>

</head>

<body>
</body>
</html>

If you open that HTML file, you'll see something like this:





That's the end of this section.  Check out part two once you have a grasp on this!

No comments:

Post a Comment