我想我得到了我自己的问题的答案。将尝试在这里解释它。
无法通过使用D3JS编写的JS函数来验证图形是否被正确绘制。为此,我们可能不得不使用Chrisopher提到的Phantom.js或类似的框架。我并不担心确保D3JS正确地绘制图形,因为任何方式都是D3JS功能,我的代码可以安全地假定D3JS正在完成其工作。
我的担心更多的是传递给D3JS的数据是否正确并符合我的要求。通过创建间谍对象来确保图形的属性是非常可能的。我正在提供一个样本单元测试,其中包含使用D3JS绘制Circle的JS代码的测试用例。
CircleManager.js
function CircleManager() {};
CircleManager.prototype.draw = function(radius) {
var svg = d3.select("body")
.append("svg");
svg.attr("width", 100)
.attr("height", 100);
var circle = svg.append("circle");
circle.style("stroke", "black")
.style("fill", "white")
.attr("r", radius)
.attr("cx", 50)
.attr("cy", 50);
};
CircleManagerSpec.js
describe("draw", function() {
it("Constructs an svg", function() {
var d3SpyObject = jasmine.createSpyObj(d3, ['append', 'attr']);
// Returns d3SpyObject when d3.select method is called
spyOn(d3, 'select').andReturn(d3SpyObject);
var svgSpyObject = jasmine.createSpyObj('svg', ['append', 'attr', 'style']);
// Returns svgSpyObject when d3.select.append is called.
d3SpyObject.append.andReturn(svgSpyObject);
d3SpyObject.attr.andCallFake(function(key, value) {
return this;
});
svgSpyObject.append.andReturn(svgSpyObject);
svgSpyObject.attr.andCallFake(function(key, value) {
return this;
});
svgSpyObject.style.andCallFake(function(key, value) {
return this;
});
var circleManager = new CircleManager();
circleManager.draw(50);
expect(d3.select).toHaveBeenCalledWith('body');
expect(d3SpyObject.append).toHaveBeenCalledWith('svg');
expect(svgSpyObject.attr).toHaveBeenCalledWith('r', 50);
expect(svgSpyObject.attr).toHaveBeenCalledWith('width', 100);
expect(svgSpyObject.attr).toHaveBeenCalledWith('height', 100);
expect(svgSpyObject.style).toHaveBeenCalledWith('stroke', 'black');
expect(svgSpyObject.style).toHaveBeenCalledWith('fill', 'white');
});
});
希望这有助于。
我总是会测试任何与数据相关的部分,然后用d3来绘制数据。因此,例如,如果你正在创建一个累积线图,我会检查[0,5,2,1]是否转换为[0,5,7,8],然后应用于选择和黎明(以及那些不常见的情况优雅地处理)。有兴趣看看还有其他什么。 –
这样做的一种方法是使用[Selenium](http://docs.seleniumhq.org/)。 –
您可能需要查看我的答案,我已编辑它。我不同意你的回答,并解释了理由。希望它会有所帮助。 – Hafiz