Disabling all D3 animations (for testing)

前端 未结 4 1503
旧巷少年郎
旧巷少年郎 2020-12-30 00:36

I\'m looking for a D3 equivalent to jQuery.fx.off = true.

Say you are writing tests (with Mocha, QUnit, etc.) for an app that uses D3. The app has some D3 animations

相关标签:
4条回答
  • 2020-12-30 00:46

    One approach you could take is to use a fake timer in your testing suite, like Sinon, which works with Mocha or QUnit. Jasmine also has a mock timer built in. I'd think this a better approach because it means the code you're testing is closer to the running code (as opposed to sabotaging the transition functions).

    0 讨论(0)
  • 2020-12-30 00:54

    An alternative to mocking out transitions is executing them synchronously directly to their final state.

    With D3.js v4, use:

    function flushAllD3Transitions() {
        var now = performance.now;
        performance.now = function() { return Infinity; };
        d3.timerFlush();
        performance.now = now;
     }
    

    With D3.js v3 and previous, do:

    function flushAllD3Transitions() {
        var now = Date.now;
        Date.now = function() { return Infinity; };
        d3.timer.flush();
        Date.now = now;
     }
    

    See also d3 issue 1789.

    0 讨论(0)
  • 2020-12-30 00:57

    Seems like you can mock d3.timer function:

    var d3timer = d3.timer;
    
    d3.timer = function(callback, delay, then) {
        d3timer(callback, 0, 0);
    };
    
    0 讨论(0)
  • 2020-12-30 01:11

    I do not know of a native way to do it in d3. But you can easily modify the d3 selector API to skip animations by augmenting the d3 prototypes:

    HTML code to be animated:

    <svg width="200" height="200">
        <rect x="1" y="1" width="0" height="100" />
    </svg>
    

    Animation and D3-augmentation code:

    function animate(color){
        d3.selectAll("rect")
        .attr("width", 0).attr("fill", "white")
        .transition().duration(1000)
        .attr("width", 100).attr("fill", color)
    }
    
    function augment(){
        // add a duration function to the selection prototype
        d3.selection.prototype.duration   = function(){ return this }
        // hack the transition function of d3's select API
        d3.selection.prototype.transition = function(){ return this }
    }
    
    animate("red")
    console.log("normal animation done")
    setTimeout( function(){
            augment()
            console.log("d3 hacked!")
            animate("green")
            console.log("animation skipped")
    }, 1200 )
    

    Attention! This hack may not work as a complete solution for you. You may want to extend this solution with other transition().* functions that are not available on the d3.selection.prototype and that you use in your application. You may also consider other forms of animation supported by d3. Maybe there is more than <selection>.transition() that I am not aware of.

    0 讨论(0)
提交回复
热议问题