与Chai反应的单元测试d3v4缩放行为

时间:2017-09-12 05:28:59

标签: reactjs unit-testing d3.js svg chai

使用d3v4,react和chai(chai-enzyme,chai-jquery)进行单元测试。

所以我的缩放行为附加到我的图表中。

const zoom = d3
  .zoom()
  .scaleExtent([1, Infinity])
  .on('zoom', () => {
    this.zoomed()
  })

缩放行为附加到svg元素。

const svg = d3
  .select(this.node)
  .select('svg')
  .attr('preserveAspectRatio', 'xMinYMin meet')
  .attr('viewBox', `0 0 ${svgWidth} ${svgHeight}`)
  .classed('svg-content-responsive', true)
  .select('g')
  .attr('transform', `translate(${margin.left},${margin.top})`)
  .attr('height', height + margin.top + margin.bottom)
  .attr('width', width + margin.left + margin.right)
  .call(zoom)

on('zoom')回调定义为

zoomed () {
 const {gXAxis, plotPlanText, plotZones, width, xAxis, xScale} = this.graphObjects
 const transform = d3.event.transform

 // get xMin and xMax in the viewable world
 const [xMin, xMax] = xScale.domain().map(d => xScale(d))

 // Get reverse transform for xMin and xMax.
 if (transform.invertX(xMin) < 0) {
   transform.x = -xMin * transform.k
 }
 if (transform.invertX(xMax) > width) {
   transform.x = xMax - width * transform.k
 }

 // transform the bars for zones

 if (!isNaN(transform.x) && !isNaN(transform.y) && !isNaN(transform.k)) {
   // rescale the x linear scale so that we can draw the x axis
   const xNewScale = transform.rescaleX(xScale)
   xAxis.scale(xNewScale)

   // rescale xaxis
   gXAxis.call(xAxis)

   plotZones
     .selectAll('rect')
     .attr('x', (d, i) => transform.applyX(xScale(d.maxFrequency)))
     .attr('width', (d) => -(transform.applyX(xScale(d.maxFrequency)) - transform.applyX(xScale(d.minFrequency))))

   // transform  the flow text
   plotPlanText
     .selectAll('.plan-text-src')
     .attr('x', d => (transform.applyX(xScale(d.maxFrequency)) + transform.applyX(xScale(d.minFrequency))) / 2)
   plotPlanText
     .selectAll('.plan-text-dest')
     .attr('x', d => (transform.applyX(xScale(d.maxFrequency)) + transform.applyX(xScale(d.minFrequency))) / 2)
 }}

启动“缩放”事件的单元测试是

describe('d3 Event handling', function () {
  beforeEach(function () {
    $.fn.triggerSVGEvent = function (eventName, delta) {
      let event = new Event(eventName, {'bubbles': true, 'cancelable': false})
      if (delta) {
        event.deltaX = delta.x
        event.deltaY = delta.y
      }
      this[0].dispatchEvent(event)
      return $(this)
    }
  })

  describe('When the chart is zoomed', function () {
    let initialX
    beforeEach(function () {
      $('.flow-zone-container > svg > g').triggerSVGEvent('wheel')
    })
    it('should update elements when zoomed', function () {
      ...
    })
  })
})

当我使用chai-jquery触发“wheel”事件时,会触发zoom事件,但zoomed()方法中的d3.event.tranform会为x,y和k提供NaN。我想测试zoomed()回调,以便我有d3.event.transform值来测试zoomed()方法中的逻辑。

如何使用“wheel”事件或任何其他事件触发zoomEvent,以便使用某些值触发d3.event?

1 个答案:

答案 0 :(得分:0)

解决了这个问题。我现在使用zoomBehaviour.scaleBy(selection, scale)来触发回调,而不是使用jquery来触发事件。