【发布时间】:2018-01-01 12:09:56
【问题描述】:
这是一个在 react 组件中使用的函数。如您所见,我使用 ref 将焦点放在另一个组件的特定输入元素上。
myFunction (param) {
this.refInput && this.refInput.focus()
}
现在我想通过 jestJS 测试 focus() 是否已被调用。
it('myFunction() should call focus()', () => {
// SETUP
const refInput = { focus: jest.fn() }
wrapper = shallow(<Example
refInput={refInput}
/>)
// EXECUTE
wrapper.instance().myFunction('anything')
// VERIFY
expect(refInput.focus).toHaveBeenCalled()
})
但这是错误的,因为我将 refInput 作为属性传递。但它不是this.props.refInput,所以这个尝试行不通。
如何在我的测试中设置 ref?
更新
这是我的组件的样子:
class Example extends Component {
setStep (state) {
state.term = ''
this.setState(state)
this.refInput && this.refInput.focus()
}
render () {
return (
<div>
<Step onClick={this.setStep.bind(this, this.state)}>
<Step.Content title='title' description='description' />
</Step>
<Input ref={input => { this.refInput = input }} />
</div>
)
}
}
【问题讨论】:
-
浅渲染不维护内部实例,因此它不能保存引用。我认为为了测试 ref 你必须安装组件。看看 MountedRenderer
-
你使用的是哪个版本的 react?如果是 15.4.0 或更高版本,请查看:reactjs.org/blog/2016/11/16/…。如果你明确想要测试 DOM 节点,你必须使用 Enzime (airbnb.io/enzyme/docs/api/ReactWrapper/ref.html)
-
@MarouenMhiri 我正在使用 React 16 和 Enzyme...
标签: javascript reactjs unit-testing jestjs