Saturday, October 22, 2011

Getting started with Jasmine in Visual Studio

You've probably heard good things about the Javascript testing framework known as Jasmine. Hopefully you've given it a test run over at http://try-jasmine.heroku.com. It is a quick way to unit test a small class or set of functions and see the red-light/green-light statuses.

Start by downloading the standalone Jasmine at https://github.com/pivotal/jasmine/wiki. Copy the jasmine folder to your web project. As of version 1.1.0 the contents are jasmine.css, jasmine.js, and jasmine-html.js (and a .png icon). For some reason there was no specrunner.htm file as indicated by the instructions.

The next step is to create the specrunner.htm file mentioned above. This will be the single file used to run a suite of all tests for the project. I created a file named **specrunner.htm** at the root of the project.

In the HEAD section you'll want to link the main jasmine javascript and css files. After that you'll want to link your javascript code that will be tested. The third thing to link will be your javascript test files or spec files as jasmine refers to them as. The final step needed for you page is to put script tags in the BODY section to execute the test runner. Below is a sample completed html page with all needed elements that tests one javascript file and has one spec file.
<!DOCTYPE html>
<html>
<head>
    <title>Jasmine Tests</title>
    
    <!-- Files required for Jasmine -->
    <link href="Content/scripts/jasmine-1.1.0/jasmine.css" rel="stylesheet"/>
    <script type="text/javascript" src="Content/scripts/jasmine-1.1.0/jasmine.js"></script>
    <script type="text/javascript" src="Content/scripts/jasmine-1.1.0/jasmine-html.js"></script>
    
    <!-- Javascript files to be tested -->
    <script type="text/javascript" src="Content/scripts/numberConverter.js"></script>

    <!-- Spec files holding the tests -->
    <script type="text/javascript" src="Content/scripts/tests/numberConverterSpecs.js"></script>

</head>
<body>

    <!-- Code to run the tests and show results -->
    <script type="text/javascript">
        jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
        jasmine.getEnv().execute();
    </script>

</body>
</html>
Hopefully you're using classes in your javascript, if not then WTF are you thinking? Here is a simple js class that we'll write tests against:
var hero = (function() {
  var shieldMaterial = 'iron';
  
  return {
    blockFlames: function() {
      if (shieldMaterial != 'iron')
        return 'dead';
      else
        return 'safe';
    },
    
    dropShield: function() {
      shieldMaterial = '';
    }
  };
}());
So what does code inside a spec file look like?
describe('hero',function(){
  beforeEach(function() {
    this.addMatchers({
      toBeSafe: function() {
        return this.actual === 'safe';
      },
      toBeDead: function() {
        return this.actual === 'dead';
      }
    });
  });
  it('can fight dragon',function(){
    expect(hero.blockFlames()).toBeSafe();
  });
  it('dies after dropping shield',function(){
    expect(hero.blockFlames()).toBeSafe();
    hero.dropShield();
    expect(hero.blockFlames()).toBeDead();
  });
});
Lines 2 - 10 of the spec files are used to define two new comparison functions: toBeSafe and toBeDead in relation to our hero. Defining those two methods at the beginning allows them to be used throughout the rest of the spec file and can make our tests have more meaning within the context of our domain.

If we launch our htm page in a browser we should see something like this:

If we change our hero's shield material to 'wood' in Line 2 and refresh the page, the results will turn into this:


This is a quick way to start using Jasmine in your projects. If you want to really integrate your javascript testing into Visual Studio such that you can view the results in a test runner window, take a look at JsTestDriver and the Jasmine adapter for it.

2 comments:

  1. Hi
    I am trying to implement the same example you explained above
    But i am getting the following error.
    Can you please help me resolve it?
    Test 'hero:can fight dragon' failed
    ReferenceError: Can't find variable: $ in file:///c:/users/avpatil/documents/visual%20studio%202010/Projects/testjasmine/testjasmine/Scripts/jasmine-jquery.js (line 145)
    in c:\users\avpatil\documents\visual studio 2010\Projects\testjasmine\testjasmine\specrunner.htm (line 0)

    ReplyDelete
    Replies
    1. It sounds like you need a link to jQuery. Add this line to your specrunner.htm page somewhere above the line where you link your jasmine-jquery.js file.

      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

      Delete