Alex Gyoshev

qHint - Enforcing Coding Conventions With jsHint and qUnit

[Update: the project is now called qHint, as Leo Balter suggested]

Open-source and coding conventions

Adhering to coding conventions (other than your own) is hard. This is particularly true in the open-source world, where every project may have different style requirements. This makes code contributions harder, since you either:

  • have to remember the coding style for each project that you contribute to, or

  • submit patches that do not follow the style guide of the project (thus either scrambling the code or making the reviewers’ job harder)

Tools like jsLint solve these problems by enforcing strict rules about the coding style. However, requiring all developers to run jsLint is prone to errors, as it is yet another step in the process of contribution. This post provides a solution to this problem, for projects that have unit tests written in qUnit – but the same process can be applied for any other unit test framework.

JsHint

jsHint is a code quality tool forked from jsLint. While the latter had strict rules and pretty much tried to enforce a general coding convention, the former allows flexible customization of the rule set, so that it matches your coding standards. Its configuration is dead simple, and you get a nice array of all style violations when you call the JSHINT function.

Integrating jsHint into qUnit

Imagine that you could validate a JavaScript file against jsHint with the following line:

<code>jsHintTest('Core', '../src/core.js');</code>

It would be neat, right? Well, the following code introduces this new type of qUnit test. It fetches the specified JavaScript file and outputs any validation errors like qUnit test errors.

<code>function jsHintTest(name, sourceFile, options) {
    function validateFile(source) {
        var i, len, err,
            result = JSHINT(source, options),
            errors = JSHINT.errors;

        ok(result);

        if (result) {
            return;
        }

        for (i = 0, len = errors.length; i < len; i++) {
            err = errors[i];

            if (!err) {
                continue;
            }

            ok(false, err.reason + " on line " + err.line +
                                   ", character " + err.character);
        }
    }

    return asyncTest(name, function() {
        $.ajax({
            url: sourceFile,
            success: function(source) {
                start();
                validateFile(source);
            }
        });
    });
}

`

And the result is…

Screenshot of qUnit tests that validate coding style using jsHint

The latest qHint code is on github.

Comments