不能使用QUnit Test中声明的变量

时间:2015-04-06 21:21:04

标签: javascript qunit

我对Javascript相对较新,并且是第一次使用QUnit。 我在一个文件中创建了一些全局函数,并使用'脚本'将该文件包含到我的javaScriptTests.html文件中。标签

在javaScriptTests.html中,我已声明一个对象传递给声明的函数并返回结果。但是,测试失败了。乍一看它似乎是QUnit,但我认为实际问题可能是我在以傻瓜证明方式定义函数方面的糟糕的javascript技巧。

QUnit错误是: enter image description here

我在bradri.js中声明的函数如下所示:

var findNodeIndex = function(id, nodes){
    // return node index with a given id
    var length = nodes.length || 0; 
    for (var index=0; index < length; index++){
        if (nodes[index].name === id){
            return index;
        };      
    };
};

var buildLinks = function (nodes){
    // build the links table for d3
    var links = [],
        length = nodes.length;
    for (var i=0; i < length; i++){
        if (nodes[i].mother){
            //console.log(i, nodes[i].mother);
            links.push({source: i, target: findNodeIndex(nodes[i].mother)});
        };
        if (nodes[i].father){
            links.push({source: i, target: findNodeIndex(nodes[i].farther)});
        };
    }
    return links;
};

此文件中未定义节点。这个错误似乎表明QUnit期望var&#39;节点&#39;要在bradri.js中定义,即使这只是内部使用的节点&#39;意图从javaScriptTests.html

传入

这是我的测试结果:

QUnit.module("unrelated test", {
  setup: function() {
    // add it to current context 'this'
    this.testNodes = [
    {name: 'a', mother: '', farther: ''},
    {name: 'b', mother: '', farther: ''},
    {name: 'c', mother: '', farther: ''},
    {name: 'd', mother: '', farther: ''},
    {name: 'e', mother: '', farther: ''},
    {name: 'f', mother: 'a', farther: 'b'},
    {name: 'g', mother: 'a', farther: 'b'},
    {name: 'h', mother: 'a', farther: 'b'},
    {name: 'i', mother: 'c', farther: 'd'},
    {name: 'j', mother: 'c', farther: 'd'},
    {name: 'k', mother: '', farther: ''},
    {name: 'l', mother: 'e', farther: 'f'},
    {name: 'm', mother: 'j', farther: 'k'},
    {name: 'n', mother: 'l', farther: 'm'}
    ];
  }
});

QUnit.test( "Unit testing of custom D3 code", function( assert ) {

var result = '[{"source":5,"target":0},{"source":6,"target":0},{"source":7,"target":0},{"source":8,"target":2},{"source":9,"target":2},{"source":11,"target":4},{"source":12,"target":9},{"source":13,"target":11}]';

var temp = buildLinks(this.testNodes); // IT FAILS HERE
//JSON.stringify(temp)
//assert.equal(result, result, "We expect value to be hello" );
});

1 个答案:

答案 0 :(得分:1)

在致电nodes时,您错过了第二个findNodeIndex(nodes[i].mother);参数。将这些来电更改为findNodeIndex(nodes[i].mother, nodes);