Michael Parker Michael Parker - 2 months ago 24
React JSX Question

React's TestUtils.Simulate.keyDown does not work

I have a lot of components in my application that respond to different key presses, and so far, none of my tests that use

TestUtils.Simulate.keyDown
work at all. It seems like
keyDown
just plain and simple does not work.

Here's the component I'm trying to test:

description.js



var React = require('react/addons');

var Description = React.createClass({
render : function () {
return (
<div className="description">
<input type="text" ref="input"/>
</div>
)
}
});

module.exports = Description;


And here is a simple test that is failing:

description-test.js



var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var expect = require('expect');
var Description = require('../description');

describe('Description', function () {
it('updates input value on key press', function () {
var description = TestUtils.renderIntoDocument(<Description/>);
var input = React.findDOMNode(description.refs.input);
expect(input.value).toEqual(''); //This passes
TestUtils.Simulate.keyDown(input, {key : "a"});
expect(input.value).toEqual('a'); //This fails
});
});


I have multiple tests that rely on
TestUtils.Simulate.keyDown
. These tests try a multitude of different keys to press (with Enter being the most prominent), but none of them work. I've tried using
keyPress
and
keyUp
, not knowing if those functions even exist at all (shoutout to the surprisingly incomplete documentation).

Am I just using the function incorrectly? Or is there something else wrong here?

I'm using karma-cli via npm to run my tests, if that makes a difference.

Answer

I ended up figuring out the issue.

TestUtils.Simulate.keyDown(input, {key : "a"});

This line sends an event to the correct DOM node, but the event data doesn't actually contain a keyCode, which is what the code is looking for. Why the official documentation specifically says you should use key is beyond me.

For it to function correctly, the following modification needed to be made:

TestUtils.Simulate.keyDown(input, {keyCode : 65});

I hope this helps out someone else with a similar issue.

Comments