我正在尝试将 mocha 用于一些测试驱动开发。仍然在开始涉足软件工程时,我遇到了一个问题,包括 test.js 中的 Graph.js:
项目/图表/Graph.js:
function Graph(){
this.nodes = {};
this.id = 0;
}
Graph.prototype.newId = function(){
return this.id++;
};
Graph.prototype.addNode = function(data){
var node = new Node(graph, this.newId());
node.data = data || {};
this.nodes[node.id] = node;
return edge.id;
};
Graph.prototype.removeNode = function(node){
for(var key in this.nodes){
for(var key2 in this.nodes[key].to){
if(this.nodes[key].edges.to[key2] == this){
delete this.nodes[key].edges.to[key2];
}
}
for(var key2 in this.nodes[key].from){
if(this.nodes[key].edges.from[key2] == this){
delete this.nodes[key].edges.from[key2];
}
}
}
delete this.nodes[node.id];
return 0;
};
Graph.prototype.addEdge = function(source, target){
id = this.newId();
source.edges.to[id] = target;
target.edges.from[id] = source;
return id;
};
Graph.prototype.removeEdge = function(edgeId){
delete this.edges[edgeId];
};
function Node(graph, id){
this.id = id;
this.graph = graph;
this.edges = {};
this.edges.from = {};
this.edges.to = {};
};
exports.Graph = Graph;
exports.Node = Node;
项目/测试/test.js:
require('../Graph/Graph.js');
suite('Graph.js', function(){
setup(function(){
var graph = new Graph();
var n0 = graph.addNode({text: "Hello"}),
n1 = graph.addNode({text: "Sweet"}),
n2 = graph.addNode({text: "Worlds!"});
var e0 = graph.addEdge(n0, n1),
e1 = graph.addEdge(n1, n2);
});
test('traverse graph', function(){
var currentNode = n0;
var str = ''
while(Object.keys(currentNode.edges.to).length > 0){
str += currentNode.data.text + ' ';
currentNode = currentNode.edges.to[Object.keys(currentNode.edges.to)[0]];
}
assert.equals(str, 'Hello Sweet Worlds! ');
});
});
用命令
localhost:testing lowerkey$ mocha -u tdd -R nyan
我得到以下结果:
0 -__,------,
1 -__| /\_/\
0 -_~|_( o .o)
-_ "" ""
✖ 1 of 1 test failed:
1) Graph.js "before each" hook:
ReferenceError: Graph is not defined
at Context.<anonymous> (/Users/lowerkey/Desktop/TryThree/testing/test.js:5:19)
at Hook.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:200:32)
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:201:10)
at Runner.hook (/usr/local/lib/node_modules/mocha/lib/runner.js:212:5)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
更新,我得到未定义的图形(小写)var graphjs = require(...);
。var graph = new graphjs.Graph();