2015-04-06 60 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