Today we're going to take a really quick look at setting up the Jasmine testing library for Javascript. Jasmine is a behaviour driven development framework, usually abbreviated BDD, and essentially means that we are using natural language to describe our tests and their expected results. 

The first thing that we're going to want to do is install Jasmine and its CLI tools.

npm install -g jasmine

Now inside your project directory you can create a simple test folder and configuration file.

jasmine init

Cool. Now we should have a spec folder to place our test files and a basic jasmine.json config file, which we'll take a look at below. 

jasmine.json

{
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.js"
  ],
  "helpers": [
    "helpers/**/*.js"
  ],
  "stopSpecOnExpectationFailure": false,
  "random": false
}

This file is giving us a few things, the directory for our files (in this case spec), the general names of our test files (anything that ends with spec.js or Spec.js, for example, storeSpec.js), and the location of our helper files, which we can use to define custom matchers. 

The final two lines are options we can make use of to either pseudo-randomly execute our tests cases, or, in the case of stopSpecOnExpectationFailure, to immediately stop our tests upon the first failure that we find. Both of these can also be set as CLI options using --random=false and --stop-on-failure=false respectively. 

On the matter of CLI options there is another one that is pretty useful and you can find yourself using fairly often, it's the --filter option. This will let you filter and run only the given spec, so for example, --filter="should be possible to add an item to the cart", will only run the spec with the given description. 

Though less common, Jasmine can also be used as a library directly in your project, lets take a look at a simple example of this.

var Jasmine = require('jasmine');
var jasmine = new Jasmine();

jasmine.loadConfigFile('spec/support/jasmine.json');

jasmine.execute();

Here we are making use of the CommonJS syntax (though you can use whichever module syntax you prefer) to import Jasmine. The loadConfigFile property gives the path to our Jasmine config file and the .execute() function will run it. Simple as that. 

Next time, in the heftier part II, we'll dive into test writing with Jasmine's describe and it blocks, and how to handle common issues like asynchronous behaviour. 

 

-Brad