我创建了一个反应组件来充当自动保存输入字段。预期的行为是:
onSubmit
道具
用户输入的值。props.lastSavedValue
。组件的代码是:
class AutoSavingInput extends React.Component {
constructor (props) {
super(props)
this.state = {currentValue: props.lastSavedValue || ''}
}
render() {
return (
<input
ref={(input) => this.input = input}
value={this.state.currentValue}
onChange={(e) => this.setState({currentValue: e.target.value})}
onBlur={() => this.props.onSubmit(this.state.currentValue)}
onKeyUp={(event) => {
switch (event.key) {
case 'Enter':
this.input.blur()
break
case 'Escape': {
this.setState({currentValue: this.props.lastSavedValue},
() => this.input.blur())
break
}
}
}}
/>
)
}
}
使用Jest或Enzyme测试blur
事件是微不足道的,但我在测试时遇到问题
关键新闻事件。我试过了:
function setup () {
const onSubmit = jest.fn()
const component = ReactTestUtils.renderIntoDocument(
<AutoSavingInput lastSavedValue="last-saved-value" onSubmit={onSubmit} />
)
const node = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'input')
component.setState({currentValue: 'the-value'})
return { component, node, onSubmit }
}
// THIS TEST SHOULD PASS BUT IT FAILS
it('submits when Enter key is pressed', () => {
const { node, onSubmit } = setup()
ReactTestUtils.Simulate.keyUp(node, {key: 'Enter'})
expect(onSubmit).toHaveBeenCalledWith('the-value')
})
// THIS TEST SHOULD FAIL BUT IT PASSES
it('does not submit when Escape key is pressed', () => {
const { node, onSubmit } = setup()
ReactTestUtils.Simulate.keyUp(node, {key: 'Escape'})
expect(onSubmit).toHaveBeenCalledTimes(0)
})
正如评论所描述的那样,Enter键测试在应该通过和Escape键时失败
当测试失败时,测试通过。发生这种情况是因为在测试环境中,
this.input.blur()
未触发blur
事件。
当我在浏览器中测试时,代码的行为符合预期。
可以编写一个Jest或Enzyme测试来处理组件内发出的事件吗?
如果有人想要试验,我已将代码放在create-react-app项目中:https://github.com/RobbieClarken/testing-react-component-events
答案 0 :(得分:0)
看起来keyUp
事件意图触发this.input.blur()
,您希望blur()
然后触发组件的onBlur()
函数并调用{{ 1}}。这可能不是您可以使用Enzyme轻松测试的东西。实际上并没有DOM,因此您可能无法期望onSubmit()
实际上会触发输入的this.input.blur()
处理程序。您可能会更好地测试onBlur()
事件直接触发的内容(keyUp
而不是this.input.blur()
)。