使用Chutzpah测试duktape

时间:2015-06-05 09:09:54

标签: javascript visual-studio unit-testing commonjs chutzpah

我正在使用Atomic Game Engine嵌入式JavaScript引擎的游戏引擎(Duktape)中工作。这允许加载CommonJS模块,因此我有以下模块:

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);
}

我已经让Chutzpah在VS社区版中进行了单元测试(使用qunit)。测试没有使用require函数或导出对象的东西很好,测试上面的模块如下:

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

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

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

Chutzpa失败了,找不到&#34;找不到变量&#34;错误。

我通过在fakeJSCommon.js中添加以下内容来解决这个问题,然后我从测试文件中引用它:

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

但是我需要手动参考我测试的模块的要求,这看起来并不理想。

所以我的问题是:有没有办法让Chutzpah对待需要的参考标签,或者更好的方法来实现我想要的目标?

1 个答案:

答案 0 :(得分:0)

Chutzpah只是在浏览器中运行您的代码,因此您引用的任何内容都必须是可加载的有效JavaScript。如果你使用的方法是“神奇的”并且没有真正的定义,那么Chutzpah就会失败。我认为你最好的选择就是有一个垫片(就像你制造的那样)可以防止Chutzpah在声明中出错。然后添加chutzpah.json文件来声明您的引用。