gpt4 book ai didi

javascript - 无法使用 QUnit Test 中声明的变量

转载 作者:行者123 更新时间:2023-12-03 10:24:17 25 4
gpt4 key购买 nike

我对 Javascript 比较陌生,也是第一次使用 QUnit。我在一个文件中创建了一些全局函数,并使用“script”标签将该文件包含到我的 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 希望在 bradri.js 中定义 var 'nodes',即使它仅在内部使用,并且 '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" );
});

最佳答案

调用 findNodeIndex(nodes[i].mother); 时缺少第二个 nodes 参数; 将这些调用更改为 findNodeIndex(nodes[i] .mother,节点);

关于javascript - 无法使用 QUnit Test 中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com