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 are a student in the Java, PHP or C# track, you may already be familiar with unit testing tools. JavaScript unit testing works exactly the same way.

There are many JavaScript testing frameworks; two of the most popular are Jasmine and Mocha. These libraries have many similarities, and after you learn how to use one, you can quickly learn the other. Both are equally good, but we’ll focus on learning Jasmine because it’s the unit-testing framework that’s built into Angular CLI, which we’ll be learning in a few weeks.

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. First, we’ll use npm to install Jasmine. The Jasmine Node module comes with code that allows us to run our tests in the terminal. Once we’ve familiarized ourselves with Jasmine, we’ll learn to use a test-runner called Karma to run our tests.

As always, we should create a package.json file by running npm init. Now we can install the Node module for Jasmine:

$ npm install jasmine --save-dev

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:

package.json
...
"scripts": {
  "test": "jasmine"
}
...

Now we can type the command $ npm test in the terminal to run our tests!

You should see something like this:

> [email protected] test
> jasmine

Started

No specs found
Finished in 0.002 seconds