Example:
I have a React Component, List
class List extends React.Component {
static propTypes {
onFocusChange: PropTypes.func.isRequired
}
componentDidMount() {
window.addEventListener('keydown', this._handleFocusChange);
}
componentWillUnmount() {
window.removeEventListener('keydown', this._handleFocusChange);
}
@autobind
_handleFocusChange(e) {
if (e.which === 38) {
const someValue = populateThisValue();
this.props.onFocusChange(someValue);
}
}
}
Now in the corresponding test file I use React Test Utils sinon spy to mock the onFocusChange function passed in as prop:
test('onFocusChange should be called when up arrow key is clicked', () => {
const onFocusChange = sinon.stub();
ReactTestUtils.renderIntoDocument(
<List
onFocusChange={onFocusChange}
/>
);
ReactTestUtils.Simulate.keyDown(window, { which: 38 });
assert.isTrue(onFocusChange.calledOnce);
assert.isTrue(onFocusChange.calledWith(0));
});
But unfortunately onFocusChange is not being called. I was initially skeptical that componentDidMount() is not being called but I checked and it is.
My guess is that the reference to window that List has is different from the one that is being used in the test.
I am not completely sure how renderIntoDocument() function on React TestUtils actually renders the component and whether its being rendered into window.document.body at all.
Can anyone help me with this?
Aucun commentaire:
Enregistrer un commentaire