React的TestUtils.Simulate.keyDown不起作用

我的应用程序中有很多组件响应不同的按键,到目前为止,我的testing都没有使用TestUtils.Simulate.keyDown 。 看起来像keyDown只是简单而简单的不起作用。

这是我正在testing的组件:

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; 

这是一个简单的testing失败:

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

我有多个依赖于TestUtils.Simulate.keyDowntesting。 这些testing尝试了许多不同的按键(使用Enter是最显眼的),但是没有一个能够工作。 我试过使用keyPresskeyUp ,不知道这些函数是否存在(喊出令人惊讶的不完整的文档)。

我只是不正确地使用该function? 还是在这里有什么不对?

我通过npm使用karma-cli来运行我的testing,如果这有所作为。

我结束了解决这个问题。

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

这一行发送一个事件到正确的DOM节点,但事件数据实际上并不包含keyCode ,这是代码正在寻找。 为什么官方文件特别说你应该使用key是超越我。

为了正常工作,需要进行以下修改:

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

我希望这可以帮助有类似问题的其他人。

TestUtils.Simulate实际上并不改变值,而是模拟目标元素上的事件。 所以,如果你的input有一个onKeyDown处理程序,用TestUtils模拟keyDown可以让你看到这个处理程序是否工作正常。

要更改input的值,可以尝试直接使用this.refs.input.value = 'a'来更改它,或者如果您有要testing的onChange处理程序,则可以模拟更改事件:

 TestUtils.Simulate.change(input, { target: { value: 'a' } }) 

只是为了logging,我有一个非常类似的问题从一个SearchInput组件发送input时引入的文本。 我有一些testing如下:

 describe('SearchInput functionality,', () => { let mockData, component, input; beforeAll(() => { mockData = { searchCriteria: "something", emptyString: " ", submitHandler: function(filter) { // storing filter param in mockData, it means SearchInput called handler successfully mockData.filter = filter; } }; spyOn(mockData, 'submitHandler').and.callThrough(); component = ReactTestUtils.renderIntoDocument( <SearchInput placeholder="Search..." onSubmit={mockData.submitHandler}/> ); input = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'input'); }); it('user writes a search criteria and hits enter', () => { input.value = mockData.searchCriteria; ReactTestUtils.Simulate.change(input); ReactTestUtils.Simulate.keyDown(input, {key: "Enter", keyCode: 13, which: 13}); expect(mockData.filter).toEqual(mockData.searchCriteria); expect(mockData.submitHandler).toHaveBeenCalled(); expect(mockData.submitHandler).toHaveBeenCalledTimes(1); }); }); 

它没有工作。

但经过一些研究后,我通过keyPress更改了keyDown ,一切正常。 原因,input键从来没有真正按下,然后input值从未发送,所有的断言失败。