Lesson Monday

In week 3 of Introduction to Programming, we learned about Behavior-Driven Development. We used BDD to break our code down to small, easy-to-test behaviors, or specs. Now it’s time to test our backend code using unit-testing tools like Jasmine.

If you're a student in the Java or C# track, you may already be familiar with unit testing tools. JavaScript unit testing works exactly the same way.

Introduction to Jasmine

There are many JavaScript testing frameworks; two of the most popular are Jasmine and Mocha. These libraries have many similarities, and after you learn to use one, you can quickly learn the other. Both are equally good.

Both Jasmine and Mocha are used for writing unit tests but they do not actually run the tests. We need a test runner for that. One option is to download the Jasmine standalone package, which comes with a SpecRunner.html file which can be used to load test results in the browser. We’ll take a different approach. Once we’ve familiarized ourselves with Jasmine, we’ll learn to use a test-runner called Karma to run our tests.


First, we’ll use npm to install a package called jasmine-core. After we install this package, we can write tests using Jasmine code.

As always, we should create a package.json file by running $ npm init. Make sure to install webpack, webpack-cli, eslint, eslint-loader and any other packages that you would like to use in this project (webpack-dev-server, clean-webpack-plugin, css-loader, style-loader, html-webpack-plugin, etc.). Don't forget to configure webpack in a webpack.config.js file and to update the scripts section of your package.json file appropriately.

Now we can install the Node module for Jasmine:

$ npm install [email protected] --save-dev

Next, we need to install a helper package for Jasmine that will allow us to use commands in the CLI to create tests with Jasmine.

$ npm install [email protected] --save-dev

Note that this command installs the latest version of jasmine-core if jasmine-core is not already added to package.json. This is why we needed to install jasmine-core first. If we wanted the latest version of jasmine and jasmine-core we would only need to run $ npm install jasmine --save-dev. However, since we want a specific version of jasmine-core we need to install it separately before installing a specific version of jasmine.

Next, we'll initialize Jasmine:

$ ./node_modules/.bin/jasmine init

Last, we’ll make a small update in our package.json file. Open it with atom and make this change:

"scripts": {
  "test": "jasmine"

Now if we run the command $ npm test our output shouldn't contain any errors and instead we should see something like this:

> [email protected] test
> jasmine


No specs found
Finished in 0.002 seconds