I want to use TestUtils.Simulate.mouseMove
on the document
. I have a component Dragger
that adds a mouseMove
event listener to the document
. Here is an incomplete version:
// Dragger.js
'use strict';
var React = require('react');
export default React.createClass({
propTypes: {
handleDrag: React.PropTypes.func // callback set by parent
},
getInitialState: function() {
return {dragging: false}
},
componentDidUpdate: function(props, state) {
//
if (this.state.dragging && !state.dragging) {
document.addEventListener('mousemove', this.onMouseMove)
} else if (!this.state.dragging && state.dragging) {
document.removeEventListener('mousemove', this.onMouseMove)
}
},
onMouseDown: function(e) {
this.setState({dragging: true})
},
onMouseMove: function(e) {
// Calls back to the parent with the drag
this.props.handleDrag(e);
},
render: function() {
return <div onMouseDown={this.onMouseDown} ></div>
}
});
I'm using jasmine, and I want to make sure my handleDrag
callback is called after a mouseDown
followed by a mouseMove
.
// Dragger.spec.js
var React = require('react/addons');
import Dragger from './Dragger';
var TestUtils = React.addons.TestUtils;
describe('Dragger', function() {
it('should call the callback after drag interaction', function() {
// make callback to spy on
var f = {callback: function(e){return}};
// render Dragger
var dragger = TestUtils.renderIntoDocument(<Dragger handleDrag={f.callback} />);
// spy on callback
spyOn(f, 'callback');
// simulate a mouseDown and mouseMove
TestUtils.Simulate.mouseDown(dragger.getDOMNode(), {button: 0});
TestUtils.Simulate.mouseMove(document);
expect(f.callback).toHaveBeenCalled(); // FAILS!
}
}
But the mouseMove
event is not being properly simulated. I see 2 problems
- I might need to pass event data to
TestUtils.Simulate.mouseMove
. For example, the callTestUtils.Simulate.mouseDown(dragger.getDOMNode())
did not work until I changed it toTestUtils.Simulate.mouseDown(dragger.getDOMNode(), {button: 0})
. What event data should I pass toTestUtils.Simulate.mouseMove
? - The
document
is not part of the detached DOM that the test component is rendered into. This could be another reason theSimulate.mouseMove
doesn't work. What can I use in the test instead ofdocument
?
How can I use TestUtils.Simulate.mouseMove
?
jasmineReact.render
which actually does render the component into an attached DOM node then cleans it up for you afterwards. While there may be several issues causing your code to not work, I believe that this will at least solve one of them – CordaliaTestUtils.Simulate.keyDown
, as I was using the (incorrect) documentation and supplyingkey
instead ofkeyDown
, which is what my code was expecting. That taught me that you can supply pretty much any kind of fake data as an argument for Simulate.keyDown (mouseMove in your case) and it will take it. – Cordalia