Gulp – Testing With Jasmine

Gulp, Gulp – Testing with Jasmine

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.

1
$ npm install karma-jasmine --save-dev

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

1
$ 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
1
2
3
4
5
6
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
1
2
3
4
5
describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(false);
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ 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
1
2
3
4
5
describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(true);
  });
});

And run our test suite again.

1
2
3
4
5
6
7
8
9
$ 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
1
2
3
4
...
gulp.task('spec-watch', function() {
  gulp.watch(['specs/**.js', 'contents/javascripts/**.js'], ['test'])
});