React的TestUtils.Simulate.keyDown不起作用 [英] React's TestUtils.Simulate.keyDown does not work

查看:81
本文介绍了React的TestUtils.Simulate.keyDown不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有很多组件可以响应不同的按键,到目前为止,使用TestUtils.Simulate.keyDown的所有测试都无法正常工作.似乎keyDown单纯和简单是行不通的.

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.

这是我要测试的组件:

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
    });
});

我有多个依赖TestUtils.Simulate.keyDown的测试.这些测试尝试按许多不同的键(其中Enter最突出),但是它们都不起作用.我试过使用keyPresskeyUp,不知道这些功能是否还存在(对令人惊讶的不完整文档大喊大叫).

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?

如果有所不同,我正在通过npm使用karma-cli来运行测试.

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

推荐答案

我最终弄清了这个问题.

I ended up figuring out the issue.

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

此行将事件发送到正确的DOM节点,但是事件数据实际上并不包含keyCode,这正是代码所要查找的.为什么官方文档专门说您应该使用key不在我的范围内.

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.

这篇关于React的TestUtils.Simulate.keyDown不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆