Nathan
Nathan

Reputation: 11159

JSLint in my unit tests

I code according to JSLint standards (excluding a couple of options) and I thought it might be a good idea to work this into my in-browser unit tests so that I don't accidentally commit anything which doesn't pass it. I'm using QUnit, but the same can probably be applied to any in-browser testing framework.

I tried this code first of all:

test("code passes JSLint", function () {
    var i, options;
    options = {
        browser : true,
        plusplus : true,
        unparam : true,
        maxlen : 120,
        indent : 4
    };

    // in QUnit `ok` is the equivalent of `assertTrue`
    ok(JSLINT(this.code, options));

    // Help me out a bit if it fails
    for (i = 0; i < JSLINT.errors.length; i++) {
        console.log(JSLINT.errors[i].line + ': ' + JSLINT.errors[i].reason);
    }
});

Edit: Forgot to mention, I declared in the setup that this.code = myFunction.toString();.

Which works great in Chrome, so I committed and continued merrily coding. When I tried it in FF, I found that FF seems to strip all the white-space out of functions when it converts them into strings, so it fails.

I'm coding and testing locally, so using AJAX to download the JS file isn't really an option. Can anyone think of a better option, or is this just a complete waste of time? (Ignoring the benefits or drawbacks of JSLint as a whole please... that's for a different discussion)

Upvotes: 1

Views: 1231

Answers (2)

SooDesuNe
SooDesuNe

Reputation: 10030

Oddly, I'm seeing the opposite behavior (fails in chrome[v17.0.x], passes in FF[v10.0.1]). Either way, another solution is to tell JSLINT to not worry about the white spaces with white:true

Your code in coffeescript, setting JSLINT to ignore whitespace:

  <script src="http://coffeescript.org/extras/coffee-script.js"></script>
  <script src="https://github.com/douglascrockford/JSLint/raw/master/jslint.js"></script>
  <script src="http://code.jquery.com/qunit/qunit-1.10.0.js"></script>

  <script>
    function myCode(){window.console.log("I have no whitespace");}
  </script>

  <script type="text/coffeescript">
    test "Code is LINT'able", ()->
      options =
        browser:true
        white:true #don't worry about whitespace
        sloppy:true #allow missing "use strict"

      ok JSLINT(myCode.toString(), options)
      JSLINT.errors.forEach (error)->
        console.log "#{error.line}: #{error.reason}"
  </script>

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150080

What is your development environment? Jslint can be integrated into common IDEs like Eclipse and (I'm pretty sure) Visual Studio. I think that would be a better option then putting it into your unit tests even if it worked perfectly in the unit tests.

Otherwise to stick with the unit test approach maybe you could put a conditional in to only run the Jslint test if in Chrome - the things Jslint checks for don't need to be tested in multiple browsers.

Upvotes: 1

Related Questions