2015-04-06 55 views
0

我对JavaScript比较新,第一次使用QUnit。 我在一个文件中创建了一些全局函数,并使用'脚本'标记将该文件包含到我的javaScriptTests.html文件中。不能使用QUnit中声明的变量测试

在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期望在bradri.js中定义var'nodes',即使这只是在内部使用,并且'节点'是要从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

你打电话findNodeIndex(nodes[i].mother);改变那些调用findNodeIndex(nodes[i].mother, nodes);

+0

Fuiii当缺少第二nodes的说法,这是快速和正确的。出色的工作和5 *加快步伐! – timebandit