vendredi 30 juin 2017

How to simulate mouseMove on d3 component for testing in react

I would like to test a component that uses D3 which reports on the competent relative coordinates of a mouseMove event. This component works as expected in the browser -- I have a simple callback that logs the coordinates and the a 'Mouse moved' event is also recorded:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { mouse, select } from 'd3-selection';

class Overlay extends Component {
  _handleMouseMove(coordinates, callback) {
    console.log('Mouse moved');
    callback(coordinates);
  }

  componentDidMount() {
    this.renderD3Move();
  }
  componentDidUpdate() {
    this.renderD3Move();
  }

  renderD3Move() {
    const handleMouseMove = this._handleMouseMove;
    const callback = this.props.callback;
    const node = ReactDOM.findDOMNode(this);
    select(node).on('mousemove', function handleMouse() {
      handleMouseMove(mouse(node), callback);
    });
  }

  render() {
    return (
      <rect
        className="overlay"
        height={this.props.height}
        width={this.props.width}
      />
    );
  }
}

export default Overlay;

Despite this, I am unable to write a test that triggers the callback or even get the 'Mouse moved' message to log:

import chai from 'chai';
chai.should();
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
import Overlay from '.';

describe('<Overlay />', function() {
  var height = 50,
    width = 50;

  it('passes mouse coordinates when mouse moves', function() {
    const callback = sinon.spy();
    var wrapper = mount(
      <Overlay height={height} width={width} callback={callback} />
    );
    wrapper.find('Overlay').simulate('mousemove');
    wrapper.find('rect').simulate('mousemove');
    wrapper.find('Overlay').simulate('mouseMove');
    wrapper.find('rect').simulate('mouseMove');
    callback.called.should.equal(true);
  });
}

My questions are:

  1. Is there a way to trigger mouseMove in the component from the test?
  2. If so, can I also test the coordinates of the mouseMove event?
  3. If there is a fundamental incompatibility with how I'm implementing the component, is there a best practice for how to determine the coordinates of a mouseMove event relative to the node that can be easily tested?

Related questions that don't fully address what I'm asking

Aucun commentaire:

Enregistrer un commentaire