D3 svg元件的Karma/Jasmine单元测试
我正在开发Angular应用程序,我使用Jasmine编写单元测试,并以测试运行者的身份编写Karma 我们正在使用D3进行可视化 我的实际代码是这样的D3 svg元件的Karma/Jasmine单元测试,svg,d3.js,Svg,D3.js,我正在开发Angular应用程序,我使用Jasmine编写单元测试,并以测试运行者的身份编写Karma 我们正在使用D3进行可视化 我的实际代码是这样的 createPlot(ds, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500); 其中,ds是我的数据,“#firstDiv”是我需要SVG的DIV的id 在createPlot中,我有如下内容 var svg = d3.select(divId).append("s
createPlot(ds, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500);
其中,ds
是我的数据,“#firstDiv”
是我需要SVG的DIV的id
在createPlot中,我有如下内容
var svg = d3.select(divId).append("svg")
.attr("width", someValue)
.attr("height", someValue);
我需要使用页面上的各种div id调用createPlot函数
这段代码实际工作并根据需要创建SVG
我的问题是:
我想使用Karma test runner为此编写jasmine单元测试
在调用“createPlot”“svg”之后,如何测试它已被创建
任何例子或帮助都将不胜感激
更新:(用下面的代码尝试了Dayan的建议,但没有成功)
description('D3页',函数(){
var-ctrl、范围、元素、编译;
var html='';
在每个(模块(“应用”)之前;
beforeach(注入(函数($controller、$rootScope、$injector、$compile){
scope=$rootScope.$new();
ctrl=$controller('D3PageCtrl'{
$scope:scope
});
compile=$compile;
element=compile(angular.element(html))(范围);
}));
在每个(函数()之后{
});
它('应该创建svg',函数(){
createPlot(ds,“#first”,“constant1”,“constant1”,“operatorsNOp”,1300500);
console.log(element.html());//打印“”
element=compile(angular.element(html))(范围);
element.scope().$digest();
console.log(element.html());//打印“”
console.log(element.find('svg').length);//打印0
expect(element.find('svg').length).toBe(1);//失败
});
});
类似的内容应作为指南:
describe('sample tests', function () {
var container;
beforeEach(function () {
container = document.createElement('div');
createPlot(container, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500);
})
afterEach(function () {
container=null;
})
it('should have svg', function () {
var svg = container.getElementsByTagName('svg');
expect(svg).not.toBe(null);
})
})
您可以创建一个div元素,不将其附加到DOM中,并将其传递给您的函数。一旦创建完毕,您应该能够遍历该元素并查看其子元素,您可以在其中执行查询,就像使用JQuery、d3或使用getElement[s]的vanilla javascript在其中附加一样[ID,TagName |…你能给我看一个代码示例吗?我是jasmine和d3的新手……如果你能发布一些代码,这将是很大的帮助。我尝试了你的建议(用我尝试过的代码更新了我的问题)。它不起作用。不确定我是否做错了什么。你能帮忙吗?你在控制台中看到了什么错误?或者在报告中看到了什么错误?我没有看到任何错误消息,除了测试失败,消息是“预期0为1”。你能做一个div的控制台日志并查看子元素吗?你有一个输入错误-“document.createElement”应该是“document.createElement”
describe('sample tests', function () {
var container;
beforeEach(function () {
container = document.createElement('div');
createPlot(container, "#firstDiv", "constant1", "constant2", "constant3", 1300, 500);
})
afterEach(function () {
container=null;
})
it('should have svg', function () {
var svg = container.getElementsByTagName('svg');
expect(svg).not.toBe(null);
})
})