Subscribe to The Rails Future        RSS Feed
-----

js - unit testing with jasmine

Icon Leave Comment
I've been working on a web application side project for several months now and I'm just now to the point where I need to start thinking about refactoring some common javascript code into separate files. That kind of a 'migration' can be very stressful and often leads to thoughts of uncertainty. For instance, there is always the chance that I will forget to manually test some functionality that the migration will have broken. If it is left broken for long enough, I will have to struggle a lot more down the road to try and remember how my code worked. Luckily, there is a way around this, and that way is called "unit testing".

The name of the javascript unit testing frame work I'll be using is jasmine, and as you can see, it's beautifully documented:

ref: http://pivotal.github.com/jasmine/


And it's mature enough to even have video tuts out there:

ref: http://www.youtube.c...h?v=ZeOKTrohqXA


Download Jasmine from here



I'm going to build some code up to be tested using jasmine, and then write a unit test from scratch.

Before we get started, you should know is ~how~ your code is tested. Well, jasmine comes with a boilerplate testing UI named "SpecRunner.html". All you have to do is make a few modifications to the top of that file and it will unit test your code once you open it in a browser.

Copy SpecRunner.html from the download zip into a new folder which will contain your project code. Also copy the "lib" directory which contains the js testing engine. At the end of this tutorial, I will present a link of the final product, so don't worry if you get out of sync.

Modifications to "SpecRunner.html"

(SpecRunner.html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>Jasmine Spec Runner</title>

  <link rel="shortcut icon" type="image/png" href="lib/jasmine-1.2.0/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="lib/jasmine-1.2.0/jasmine.css">
  <script type="text/javascript" src="lib/jasmine-1.2.0/jasmine.js"></script>
  <script type="text/javascript" src="lib/jasmine-1.2.0/jasmine-html.js"></script>


  <!-- MODIFY THIS SECTION -->
  
  
  <!-- include source files here... -->
  <script type="text/javascript" src="spec/SpecHelper.js"></script>
  <script type="text/javascript" src="spec/PlayerSpec.js"></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src="src/Player.js"></script>
  <script type="text/javascript" src="src/Song.js"></script>

  
  <!-- END OF SECTION TO MODIFY -->


  <script type="text/javascript">
    (function() {
      var jasmineEnv = jasmine.getEnv();
      jasmineEnv.updateInterval = 1000;

      var htmlReporter = new jasmine.HtmlReporter();

      jasmineEnv.addReporter(htmlReporter);

      jasmineEnv.specFilter = function(spec) {
        return htmlReporter.specFilter(spec);
      };

      var currentWindowonload = window.onload;

      window.onload = function() {
        if (currentWindowonload) {
          currentWindowonload();
        }
        execJasmine();
      };

      function execJasmine() {
        jasmineEnv.execute();
      }

    })();
  </script>

</head>

<body>
</body>
</html>






In case you missed it, the only things that need to be modified in that file are...
  <!-- MODIFY THIS SECTION -->
  
  
  <!-- include source files here... -->
  <script type="text/javascript" src="spec/SpecHelper.js"></script>
  <script type="text/javascript" src="spec/PlayerSpec.js"></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src="src/Player.js"></script>
  <script type="text/javascript" src="src/Song.js"></script>

  
  <!-- END OF SECTION TO MODIFY -->



The first paragraph of that snippet points to your javascript source files that are in your project. The second paragraph points to your unit tests which test the code of your project.

Let's change the file to point to our own source files and spec files (files that we will create later on in this entry).


  <!-- include source files here... -->
  <script type="text/javascript" src="spec/HelloSpec.js"></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src="src/Hello.js"></script>





Now let's create the project file

(src/Hello.js)
// let's create a simple object called dog that does simple things

function Dog(){
}
Dog.prototype.bark = function(){
  return "woof!";
}




Ok, now we have a simple dog object which we've taught to speak. Let's write a test to see if it can speak on command.

(spec/HelloSpec.js)
describe("The dog tests", function(){
  var dog;
  
  beforeEach(function(){
    dog = new Dog();
  });
  
  it("should be able to bark on command", function(){
    expect(dog.bark).toEqual("woof!");  // This 9th line contains an intentional error
  });
});




So now you should be able to test out your ~potentially~ working code. To do so, simple double click your "SpecRunner.html" file to automatically open it in a professional web browser like chrome or FF. When it opens, you should see something like this.

Posted Image


It's red because it failed! Our tests are not passing! Big scary deal! How do we proceed?

Well, if you haven't already caught it, and javascript being like... not a language I hold in that much regard (although I am starting to like it more and more), I made an error in the testing of bark...


If you pull down the console in chrome/FF, and try to get a dog to bark...


Posted Image






So now the correction has become much more apparent, change spec/HelloSpec.js to be...
describe("The dog tests", function(){
  var dog;
  
  beforeEach(function(){
    dog = new Dog();
  });
  
  it("should be able to bark on command", function(){
    expect(dog.bark()).toEqual("woof!");
  });
});





Refresh "SpecRunner.html" and you should see this much happier green screen...

Posted Image



Fun and easy, right? Now for manipulating DOM elements... that's another story I need to look into next week...


Here's a link to the finish product. You should be able to unzip that into a directory on your computer and open it up in a respectable web browser to see a test pass.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

September 2014

S M T W T F S
 123456
78910111213
14151617181920
21 222324252627
282930    

Tags

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)

    Categories