Jasmine Javascript Unit Tests

By | 2 December, 2012

In the same way that Java has JUnit, .NET NUnit and so on, in Javascript there’re some Unit Testing Libraries, like in this case Jasmine.  You might have not any previous experience with this sort of frameworks but Unit Testing is a must in every programming language, and Javascript isn’t an exception.

I think some things are black and white: It’s Michael.

Jasmine is a Unit Testing library to support Unit Tests in Javascript. Find the link just here: http://pivotal.github.com/jasmine/

To start with Jasmine, you need to create the following structure in your project:

Jasmine Project Structure

 Where you can find the following components:

  • SpecRunner.html: it’s the file you have to execute to lanch the tests. It’s an HTML that will be opened in the browser displaying the passed and failed tests.
  • Lib: folder which contains the libraries and files that Jasmine needs.
  • Spec: in this folder you can find all the tests definitions.
  • Src: contains the Javascript files to test.

Let’s see a basic example. Given a Javascript file which represents a music player, two methods: play and pause.

To make sure that it works, we’re going to develop some tests for this clase. For example:

In the previous test file, we have implemented three different tests (it). The first two are valid but not the third.

Finally, we only have to execute the runner file, in which we need to include all the sources that contain the code to test, and the files with the test cases. In this case the runner will be the following:

        Jasmine Spec Runner

<script type="text/javascript" src="lib/jasmine-core/jasmine.js"></script><script type="text/javascript" src="lib/jasmine-core/jasminehtml.js"></script>
        <!-- include spec files here... -->
<script type="text/javascript" src="spec/PlayerSpec.js"></script>
        <!-- include source files here... --><script type="text/javascript" src="src/Player.js"></script>
<script type="text/javascript">// <![CDATA[
            (function() {
                var jasmineEnv = jasmine.getEnv();
                jasmineEnv.updateInterval = 1000;
                var trivialReporter = new jasmine.TrivialReporter();
                jasmineEnv.specFilter = function(spec) {
                    return trivialReporter.specFilter(spec);
                var currentWindowOnload = window.onload;
                window.onload = function() {
                    if (currentWindowOnload) {
                function execJasmine() {

// ]]></script>

After executing this file, we can see the following report in our browser. You can see the passed tests in green and the failed ones  in red, with all the related information, like stack traces and error location etc

That’s all folks. Enjoy testing!

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.