JSHint with Jasmine 2

November 2, 2013 Hunter Gillane

I’ve been using Jasmine 2 on a recent project and I wanted add JSHint as part of our Jasmine build. On a previous project I had used Brandon Keeper’s approach and started there. The core of his solution works with Jasmine 2, with some slight changes. Here is an example:


describe('JSHint', function () {
  var options = {curly: true, white: true, indent: 2},
    files = /^/assets/application.js|.*spec.js$/;

  function get(path) {
    path = path + "?" + new Date().getTime();

    var xhr;
    try {
      xhr = new XMLHttpRequest();
      xhr.open("GET", path, false);
      xhr.send(null);
    } catch (e) {
      throw new Error("couldn't fetch " + path + ": " + e);
    }
    if (xhr.status  299) {
      throw new Error("Could not load '" + path + "'.");
    }

    return xhr.responseText;
  }

  _.each(document.getElementsByTagName('script'), function (element) {
    var script = element.getAttribute('src');

    if (!files.test(script)) {
      return;
    }

    it(script, function () {
      var env = jasmine.getEnv();
      var source = get(script);
      var result = JSHINT(source, options);

      _.each(JSHINT.errors, function (error) {
        env.currentSpec.addExpectationResult(false, {
          passed: false,
          message: "line " + error.line + ' - ' + error.reason + ' - ' + error.evidence
        });
      });
      expect(true).toEqual(true);
    });
  });
});

(gist is here)

Add a spec file similar to this next to your other Jasmine specs and you should see any linting errors when you run your build. The main changes from Brandon’s example are around how you tell Jasmine about a linting error. If you use an approach like this, the things you are likely to need to change are the regex for your source and spec files as well as the options used by JSHint.

Happy linting!

About the Author

Biography

More Content by Hunter Gillane
Previous
Messages Not Types: Exploring Ruby's Conversion Protocols
Messages Not Types: Exploring Ruby's Conversion Protocols

Duck typing is a style of programming that relies on what an object does, rather than on what it is. Avoid...

Next
How Bank Branches are Going to Evolve
How Bank Branches are Going to Evolve

The advent of mobile banking granted consumers the ability to pay bills, deposit cheques and, in the near f...