Friday, February 27, 2015

The Tools You Need to Get Rolling with Unit Testing Your JavaScript

(Github repo)

I love this little testing stack because you can implement it anywhere and at any time in your projects. If you’re prone to fat fingering syntax errors like myself this will also help save you time by catching those errors for you while you’re coding. Who knows, maybe even after using it for a little bit you’ll start doing Test Driven JavaScript Development(TDjsD…?)!

 

We can get all this up and running in 10 minutes.

 

How are we going to do that?

 

We’re going to run Jasmine testing framework unit tests on the Karma test runner which you’ll be running locally on Node.js.  If we have time we’ll even throw in some JSHint.

 

Sound good? Start your timer!

 

10 minutes 00 seconds

 

First we need to install Node.js if you don’t already have it.

 

I’m assuming you’re getting 100GB down from your ISP and you’re running on an SSD with 16GB of RAM. So you should be installed by now. Let’s check. Open up your favorite command prompt (as Administrator!) or terminal of choice and enter:

 

C:\> node –v
 

You should see a version number like below.

 

clip_image002

 

Are you good? Great.Let’s go!

 

8 minutes 20 seconds

 

Now that we have Node.js we can begin setting up our testing package. Node.js comes with npm which is the Node.js package manager that allows you to grab and share your own Node.js packages. If you already had Node.js installed maybe run:

 

C:\> npm install npm -g 

 

...just to make sure your npm is up to date. 

 

Now make sure you’re in the directory of your project then run the following command to set up your package:

 

C:\[my-project-folder]> npm init

 

You’ll be walked thru some prompts to setup your package.json file which will manage your new npm package.

 

Here’s what the package.json file I just created looks like:

 

{



  "name": "my-web-app",



  "version": "1.0.0",



  "description": "My web app.",



  "main": "scripts.js",



  "scripts": {



    "test": "echo \"Error: no test specified\" && exit 1"



  },



  "author": "Scot Goodhart",



  "license": "ISC"



}
 

I didn’t specify the ‘test’ option. We won’t need that for what we’re doing. #ironing

 

6 minutes 50 seconds

 

Ok, now we’re ready to install Karma!

 

C:\[my-project-folder]> npm install karma --save-dev

 

This will install Karma and all of the dependencies it needs in a new folder named ‘node_modules’ in your project’s folder. The ‘--save-dev’ flag will drop Karma(and it’s version) into your package.json so that if you or your dev friends want to use your package somewhere else they can just throw the package.json file into the directory they want to set it up in then type:

 

C:\[my-project-folder]> npm install 

…to grab all npm packages and dependencies in your module.

 

 

Speaking of package.json; it should have a new entry in it:

 

  "devDependencies": {



    "karma": "^0.12.31"



  }

 

Pretty cool, huh? I love automation.

The ‘--save-dev’ flag placed Karma in the ‘devDependencies’. There’s also a ‘--save’ flag which would put it in ‘dependencies’. The TL;DR  difference here is you wouldn’t need all of your development tools in production. 

 

Oh, to save yourself some keystrokes later let’s install the Karma Commandline Interface(cli) globally. 

 

C:\[my-project-folder]> npm install -g karma-cli

 

So later you can just type ‘karma [the file to be named later]’ to start Karma rather than ‘c:/dev/myfiles/v2/my-web-app/karma...

 

5 minutes 00 seconds

 

We need to install a few more plugins:

 

C:\[my-project-folder]> 
npm install karma-jasmine karma-chrome-launcher --save-dev

 

That’s the Jasmine/Karma adapter and the Chrome launcher for Karma. When Karma runs it’ll use Chrome to run the tests.

 

I thought we were going to also have to install Jasmine but it looks like the above command installed Jasmine-core. 

 

Let’s hope it works, yeah?

 

3 minutes 00 seconds

 

We’re so close I can almost smell the tests!

 

Now we configure our karma.config with this command:

 

C:\[my-project-folder]> karma init

 

Just like with initializing npm select all the default options and you’ll be ok.

 

Which testing framework do you want to use?

jasmine [enter]

Do you want to use Require.js?

no [enter]

Do you want to capture any browsers automatically?

chrome [enter][enter]…enter twice

What is the location of your source and test files?

(leave it blank) [enter]…enter twice

Should any of the files included in the previous patterns be excluded?

(leave it blank) [enter]…enter twice

Do you want Karma to watch all the files and runt the tests on change?

yes [enter]*

*this will keep Karma running while you code.  It’ll run the tests every time you save a file.  CTRL+C to stop it.

 

This will create karma.conf.js. Open it up. We’re going to tell it where our JavaScript and test files are.

 

// list of files / patterns to load in the browser

files: [

  'js/*.js',

  'tests/*.js'

],

 

Fill in the “glob” patterns which point to where your JavaScript and tests are….or will be. We still need to actually write a test. 


We’re running out of time!

 

1 minutes 45 seconds

 

Hurry, create a tests folder. Create a test.js file. Add in your tests. And we’re done! Oh, wait. How do you write a test? Simple. It’s a few functions:

 

//describe your block of tests

describe('The following tests are for my addition function ', function(){


  //what should the specific test do

  it('should add 5 to 3 and give me 8', function(){

    

    //a function I'm testing

    var total = myAdditionFunction(5,3);



      //what do I expect the function to do

      expect(total).toBe(8);

  });

});

 

This is of course the very tip of the iceberg. There’s some really in-depth testing you can do with Jasmine.

 

 

0 minutes 30 seconds

 

This is it!  I have an addition and a multiplication function in my scripts.js file.  Let’s see if they work:

 

C:\[my-project-folder]> karma start karma.conf.js

 

clip_image004

 

OH NO! One of my tests failed. I’ve failed you :( Or did I just show you how easy it is to test your JavaScript?!

 

Looks like my error was just Ol’ Captain Fat Fingers messing up the test file:

 

it('5 plus 3 should equal 8', function () {

  

  var total = addNumbers(5,5);

  

  expect(total).toBe(8);



});

 

0 minutes 00 seconds

 

I know we’re out of time but I think JSHint is important enough to show you. It’s like having a little annoying guy on your shoulder saying, “You forgot to close that!  You’re missing a bracket there!  Double quote your strings!!!!”  But it’ll help you code faster an