Before we start writing our unit test cases we need to set up an environment where our test cases can be executed to verify our implementation. In this recipe, we will show how this environment and necessary libraries can be set up for a visualization project.
Jasmine (http://pivotal.github.io/jasmine/) is a behavior-driven development (BDD) framework for testing JavaScript code.
We chose Jasmine as our testing framework because of its popularity in JavaScript community as well as its nice BDD syntax. You can download the Jasmine library from:
https://github.com/pivotal/jasmine/downloads
Once downloaded you need to unzip it into the lib
folder. Besides the lib
folder we also need to create the src
and spec
folders for storing source files as well as test cases (in BDD terminology test cases are called specification). See the following screenshot for the folder structure:
Now, we have Jasmine in our library, next thing to do is to set up an HTML page that will include Jasmine library as well as our source code plus test cases so they can be executed to verify our program. This file is called SpecRunner.html
in our setup which includes the following code:
<head> <meta charset="utf-8"> <title>Jasmine Spec Runner</title> <link rel="stylesheet" type="text/css" href="lib/jasmine-1.3.1/jasmine.css"> <script type="text/javascript" src="lib/jasmine-1.3.1/jasmine.js"></script> <script type="text/javascript" src="lib/jasmine-1.3.1/jasmine-html.js"></script> <script type="text/javascript" src="../../lib/d3.js"></script> <!-- include source files here... --> <script type="text/javascript" src="src/bar_chart.js"></script> <!-- include spec files here... --> <script type="text/javascript" src="spec/spec_helper.js"></script> <script type="text/javascript" src="spec/bar_chart_spec.js"></script> <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>
This code follows standard Jasmine spec runner structure and generates execution report directly into our HTML page. Now, you have a fully functional test environment set up for your visualization development. If you open the SpecRunner.html
file with your browser you will see a blank page at this point; however, if you check out our code sample you will see the following report: