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:
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:
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.
Simulate a Click Event The onClick should pass through to the component's underlying <button /> element because we're spreading ( {... props} ) that props through to it. In the test, we create a ref so that we can pass it to the rendered Button and later to the Simulate. click call.
There are a few ways to test React components. Broadly, they divide into two categories: Rendering component trees in a simplified test environment and asserting on their output. Running a complete app in a realistic browser environment (also known as “end-to-end” tests).
import React from 'react'; import ReactDOM from 'react-dom/client'; import { act } from 'react-dom/test-utils';import Counter from './Counter'; let container; beforeEach(() => { container = document. createElement('div'); document. body. appendChild(container); }); afterEach(() => { document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With