Hello Jasmine

Jasmine is a great JavaScript testing framework. Let’s prepare our environment and then build our first test in Jasmine.

Steps

Review Prerequisite Requirements

We will need the following:

  • Web Browser (almost any will do)
  • Text Editor (of any sort really)

That’s it. Nice and simple.

Create Project and Lesson Directories

  1. Create the Project directory

    We will create a project directory named introducing-jasmine which will hold many lesson directories in this series. The project directory can live really anywhere on the system. The code samples we create may be used later for reference or as a foundation for further experimentation.

  2. Create the Lesson directory

    Inside of the project directory, create a lesson directory named: 01-hello-jasmine

    At this point, the directories should look mostly like this:

    Project and Lesson Directory Image

    Project and Lesson directories.

Download Jasmine

Now let’s download Jasmine. It can be found here: http://pivotal.github.com/jasmine/download.html.

We will be using the Standalone Version of Jasmine. There is a Ruby Gem for Ruby on Rails and other situations- we won’t be looking at that here.

Deploy Jasmine

This really isn’t any sort of active deployment, we are just going to unzip and copy parts of the distribution.

  1. Unzip Jasmine and open the unzipped directory.
  2. Copy the contents of the Jasmine distribution into the lesson directory.
  3. Delete the contents of the spec and source directories. It contains sample code that we won’t be using here.

The directories should look like the below:

Lesson directory with Jasmine


Now that we have the prep work done, let’s build a test and execute it.

Note This isn’t the only way to set up Jasmine, and it isn’t a recommended way for real life projects. This is just an approach that will work well for the purposes of learning and experimenting. It also aims at making setup easy so we can move on to Jasmine more directly.

Write a Test

Using the BDD language of Jasmine, we are going to first create a Suite and inside of that suite we will create a Spec (which is the test).

  1. In the lesson directory, locate the spec directory and create a file HelloWorldSpec.js
  2. Add the below JavaScript to HelloWorldSpec.js

    // Suite
    describe("Hello Jasmine", function() {
    
        // Spec (or test)
        it("says hello", function() {
    
            // what is being tested
            function helloWorld() {
                return "Hello world!";
            }
    
            // Expectation, how we express what we expect should happen
            // our Matcher which expects the result of our function to equal "Hello world!"
            expect(helloWorld()).toEqual("Hello world!");
    
        });
    
    });

    We have just created our first Test Suite, named “Hello Jasmine” with our first Spec “says hello”. We are using a Matcher to check the results of our function.

  3. Update the Runner that will be running our tests. With a text editor, open the file SpecRunner.html and update only the Source and Spec file sections.

    <!-- Source files -->
    <!-- None for now-->
    
    <!-- Spec files -->
    <script type="text/javascript" src="spec/HelloWorldSpec.js"></script>
    

    We are pointing our Runner at only the Spec and ignoring the source for now.

Our first Spec is now ready, so let’s run it.

Run the Test

All we need to do is open the test runner in a web browser and our test will be executed.

  1. Open a Web Browser
  2. From the web browser, use the open file facility, (or a URL if the runner is deployed to a Web Server) to open the Runner SpecRunner.html
  3. Inspect the results. It should show a passing test like the below:
    Jasmine Passing Test Runner

    Intuitive language showing that in fact "Hello Jasmine says hello"

Food for thought

Below are some question that may help us think about what we have done so far:

  • How does the runner respond when the test fails? How would the spec need to be changed to force a failure?
  • What are some of the positive and negative ramifications of having the Jasmine lib in the lesson directory as opposed to some where else?

Learn More

We have built and executed our first test- we are now ready to dig into Jasmine.

Thanks to the simplicity of the tools, setting up our first test was a breeze and required very little tooling or configuration. Deployment was hardly a concern since these tests run as simple HTML and JavaScript.

Much more information on Jasmine can be found looking at the Documentation.

What is Jasmine?

Jasmine Logo

Jasmine is a behavior-driven development framework for testing your JavaScript code. [...] And it has a clean, obvious syntax so that you can easily write tests.

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

Jasmine is a popular and lightweight unit testing framework for JavaScript. It lives as github open source project and was created by the folks at Pivotal Labs.

Pivotal Labs

Pivotal Labs is a leader in Agile Software development, and it is wise to keep an eye on what they are doing. They are driving lots of good things in the industry – Jasmine being one, and also their Pivotal Tracker product being another.

Pivotal Tracker (an Agile Project Management tracking tool) is exactly what you want from JavaScript application – lightweight, responsive, and productive.

It is worth exploring the other projects that Pivotal have kicked off, including frameworks for mobile development. For the moment our focus is JavaScript and thanks to Pivotal Labs we have Jasmine, so let’s dig into it.

Fear & Test Driven Development

Jasmine is an evolution in a rich and interesting history of Test Driven Development.

“Developers face complex programming challenges every day, yet they are not always readily prepared to determine the best solution. More often than not, such difficult projects generate a great deal of stress and bad code. To garner the strength and courage needed to surmount seemingly Herculean tasks, programmers should look to test-driven development (TDD), a proven set of techniques that encourage simple designs and test suites that inspire confidence.”

Kent Beck, Test Driven Development

Frameworks like Jasmine helps us grow and understand the JS landscape with less fear using a testing language that reads well. Without tests, as applications grow, we may find “the fear” encroaching- fear from refactoring, fear of change; the exact place you don’t want to be as a developer. We want to be agile, fearless to make the right change to adapt and to sleep well at night. Instead of being the big lumbering truck slowing floating down the road weary of any sharp turns or adjustments to the road, we want to be on the little scooters zipping in and out of traffic. We dodge in and out of the traffic that constantly changes.

There are many good resources on the subject of TDD, but Beck’s Test Driven Development started things off and is still a great read as many of the main arguments haven’t changed. One of the key ideas is that in order to avoid fear of change and thus to be more agile, is to have automated systems that quickly let you know if the adjustments you make will break the existing software. As the size and complexity of the project grows, it becomes impossible to know all of the effects one will have when making changes. Complexity breeds fear, fear prevents you from being agile in a changing environment. Thus, systems that help you deal with complexity (a dependable battery of diagnostic unit-level tests) will help you be able to adapt to change. Your tests will tell if you should be afraid- afraid that you broke what was working before, otherwise have no fear everything is working just fine.

Evolving the Language of Tests

It is ironic that a common complaint of software engineers is that they aren’t good communicators and yet they are masters of many languages. The core of communication is language, and the core of software engineering is language- development languages. Languages are our tools and when we find ourselves in place where things can’t be done easily and clearly then our tools haven’t properly evolved. The most common ways to improve tools in this landscape is to augment existing languages and develop new ones.

Requirements and stories are captured in language as well. So we find a layering of languages that many people use to define and develop software. Unit Tests, as a language, are low-level and traditionally have been quite separate from the behaviour-level language that is used in story descriptions. Behaviour-driven development or BDD is an evolution of TDD to try and find leverage by bridging the gap between the language of tests and the language of story descriptions. Less integration of languages (translation) later in the process is needed.

A proper resource on the topic, via is: The Cucumber Book: Behaviour-Driven Development for Testers and Developers.

Enter Jasmine

Jasmine is quite popular, lightweight, and clean. Like all tools, Jasmine has its own qualities and very well may be the right tool for the job for a particular JavaScript project. JavaScript projects need tests. If complex projects are mountains, and developers mountain climbers, then Jasmine is the equipment to prevent us from falling too far so we can go for the more risky climbs. It helps us face our fears and describe in an accessible language exactly what we are doing.

What’s Next?

Let’s build our first test using Jasmine.