Search code examples
javascriptvisual-studiounit-testingcommonjschutzpah

Using Chutzpah to test CommonJS modules used in duktape


I'm working in a game engine (Atomic Game Engine) which uses the Duktape embeddable javascript engine. This allows loading of CommonJS modules, so I have modules like the following:

require("Scripts/LumaJS/Interface");

// Interface to be implemented by state objects
var IState = new Interface({
    optional: ["onEnter", "onExit", "onUpdate"],
    reserved: ["label"]
});

StateMachine = function(onStateChanged) {
    this.states = {};
    this.currentState = null;
    this.onStateChanged = onStateChanged;
    this.log = false;
}

StateMachine.prototype.addState = function (label, stateOrOnEnter, onExit, onUpdate) {
    // Support objects or individual functions
    var state;
    if (!stateOrOnEnter ||
        typeof (stateOrOnEnter) == "function") {
        state = {
            onEnter: stateOrOnEnter,
            onExit: onExit,
            onUpdate: onUpdate
        };
    } else {
        state = stateOrOnEnter;
    }

    // Validate and add
    IState.throwIfNotImplementedBy(state);
    state.label = label;
    this.states[label] = state;
}

StateMachine.prototype.getCurrentStateLabel = function() {
    return this.currentState ? this.currentState.label : null;
}

// Many more class functions..

exports.create = function (onStateChanged) {
    return new StateMachine(onStateChanged);
}

I've got Chutzpah set up to unit test in VS Community Edition (with qunit). Testing something that doesn't use the require function or export object is fine, testing the above module as follows:

/// <reference path="..\Resources\Scripts\LumaJS\stateMachine.js" />

test("starts with no state", function() {
    var stateMachine = new StateMachine();

    equals(stateMachine.getCurrentStateLabel(), null);
});

Chutzpa fails with a "Can't find variable" error.

I've got around this by adding the following in a fakeJSCommon.js which I then reference from test files:

require = function () { }
exports = {};

But I then need to manually reference the requires from the modules I'm testing as well, which doesn't seem ideal.

So my question is: Is there a way to get Chutzpah to treat requires like reference tags, or a better way to do this that would achieve what I'm looking for?


Solution

  • Chutzpah just runs your code in the browser so anything you reference needs to be valid javascript that it can load. If you are using methods that are "magic" and have no real definition than Chutzpah will fail on them. I think you best option is to have a shim (like you made) which prevents Chutzpah to not error on the statement. And then add a chutzpah.json file to declare your references.