【发布时间】:2018-05-02 12:29:23
【问题描述】:
我创建了一个反应组件来充当自动保存输入字段。预期的行为是:
- 如果用户按 Enter 或在框外单击,它将调用其
onSubmit属性 用户输入的值。 - 如果用户按下 Escape 键,它会将值重置为
props.lastSavedValue。 - 当按下 Enter 或 Escape 时,输入字段会散焦。
组件的代码是:
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)
})
正如 cmets 所描述的,Enter 键测试在应该通过时失败,而 Escape 键测试失败
测试在它应该失败时通过。发生这种情况是因为在测试环境中,
this.input.blur() 没有触发 blur 事件。
当我在浏览器中测试时,代码的行为符合预期。
是否可以编写一个 Jest 或 Enzyme 测试来处理从组件内部发出的事件?
如果有人想进行实验,我已将代码放在此处的 create-react-app 项目中:https://github.com/RobbieClarken/testing-react-component-events
【问题讨论】:
标签: reactjs unit-testing testing jestjs enzyme