javascript - Jasmine 在 d3 中测试鼠标悬停事件

标签 javascript jquery d3.js jasmine jasmine-jquery

我正在考虑使用 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/

相关文章:

javascript - jquery 延迟更改排队函数关闭?

php - 使用 AJAX 启动和停止 php 文件

jquery - 如何在调用 ajax 时隐藏页面并显示正在加载的 div

svg - 如何在圆弧路径元素的两端获得箭头?

javascript - 避免使用交叉过滤器的直流供电 d3 气泡图的负轴值

javascript - 当单独定义列时使用 D3 加载 JSON

javascript - 无法在纯 JS 中组合 setInterval() 和 if(confirm())

javascript - 在另一个 iframe 中查找 iframe?

javascript - 将包装函数应用于导入的函数

javascript - 在动态创建的按钮上添加单击事件,单击后更改模态 h4 文本