我正在考虑使用 d3.js 制作交互式图表元素
我正在尝试使用 jasmine 测试由于鼠标悬停事件导致的填充颜色变化。理想情况下,我希望路径元素的颜色在鼠标悬停时更改为“#ff0000”,但我的 jasmine 终端告诉我这没有发生 - 该元素似乎保持与初始设置相同的颜色,例如我的元素 id #1 产生:预期“#1f77b4”为“#ff0000”。
我也在使用 jquery 和 jasmine-jquery 库。
我的圆环图夹具 DonutChartFixture.html 中的相关代码
var color = d3.scale.category20();
var path = svg.selectAll("path")
.data(pie(data))
.enter().append("path").attr("class", "path")
.attr("fill", function(d, i) { return color(i); })
// removed id declaration here
.attr("d", arc)
.on("mouseover", function(){d3.select(this).style("fill", "#ff0000");})
.on("mouseout" , function(){d3.select(this).style("fill", function(d) {
return d.color;
});});
// want to highlight the first path element
var path_one = d3.select('.path').attr("id", "path_one");
还有来 self 的规范文件 DonutChart.js 的测试
function loadDonutChart() {
loadFixtures('DonutChartFixture.html');
}
describe("Mouseover events", function() {
var spyEvent;
beforeEach(function() {
loadDonutChart();
});
// updated test for element d3.select('.path').attr("id", "path_one")
it("#path_one should change fill colour to rgb(255,0,0)", function() {
spyEvent = spyOnEvent('#path_one', 'mouseover');
$('#path_one').trigger("mouseover");
// expect('mouseover').toHaveBeenTriggeredOn('#path_one');
expect(path_one.style('fill')).toEqual('rgb(255,0,0)');
});
});
如您所见,我已尝试按 ID 和标签名称选择元素,但均无济于事,两者都产生与上述相同的读数。干杯。
最佳答案
所以我想出了一个通过测试,主要是受到这里提供的答案的启发,Testing Mouseover event in D3 with Sinon .唯一真正的区别是使用 d3/jasmine 语法代替 Sinon。以下正确通过:
it("#path_one should change fill colour to rgb(255,0,0)", function() {
var oldColor = path.style('fill');
document.getElementById('path_one').dispatchEvent(new MouseEvent('mouseover'));
expect(d3.select('#path_one').style('fill')).not.toEqual(oldColor);
});
关于javascript - Jasmine 在 d3 中测试鼠标悬停事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23897392/