Testing with Jasmine

Learning Gulp : part 12 of 22 published on Aug 10, 2015

We all know we test our JavaScript. … you do test your JavaScript right?

Well… you should and with gulp + Karma + Jasmine it is super easy.

First if you have not installed Karma and Jasmine, then do so now.

$ npm install karma-jasmine --save-dev

Next we will install the gulp-jasmine plugin for gulp.

$ npm install gulp-jasmine --save-dev

We can then create a test task to run all the specs found in a specs folder we will create.

// gulpFile.js
var jasmine = require('gulp-jasmine');
...
gulp.task('specs', function () {
  return gulp.src('specs/**.js')
    .pipe(jasmine());
});

Let’s create a basic (failing) test to see that it is working.

// specs/our_test.js

describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(false);
  });
});
$ gulp specs
Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'specs'...
F

Failures:

  1) OMG a JavaScript Test should pass
  1.1) Expected true to be false.

1 spec, 1 failure
Finished in 0.004 seconds
'specs' errored after 39 ms Tests failed

Now it is time to refactor. We will make the extremely difficult change from false to true to make our test pass. :)

// specs/our_test.js

describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(true);
  });
});

And run our test suite again.

$ gulp specs
Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'specs'...
.

1 spec, 0 failures
Finished in 0 seconds
Finished 'specs' after 39 ms

Next we will do is improve our testing task by adding a test-watch task to run as we edit our JavaScript files.

// gulpFile.js
...
gulp.task('spec-watch', function() {
    gulp.watch(['specs/**.js', 'contents/javascripts/**.js'], ['test'])
});

Now when we edit our JavaScript files or our Jasmine specs, the tests will run.

Congratulations, we are offical JavaScript testing wizards.

Next: Creating a webpage