React/JestJS/Enzyme: How to test for ref function?

与世无争的帅哥 提交于 2019-12-08 20:38:16

问题


I'm running unit tests using Jest and Enzyme for this very simple component render():

render() {
  return (<Input
    id='foo'
    ref={input => { this.refInput = input }}
  />)
}

it('should render Input', () => {
  wrapper = shallow(<Component />)
  expect(wrapper.find(Input)).toHaveLength(1)
})

I'm also using the coverage option of Jest and there I see, that the line

ref={input => { this.refInput = input }}

is not covered by my test. What do I have to do to get a full covered unit test for this sample component?


回答1:


The ref is attached to an instance of the component hence you will have to use mount to get an instance of the component.

To test for the ref, add the following line

expect(wrapper.instance().refInput).toBeTruthy();

Final result:

render() {
  return (<Input
    id='foo'
    ref={input => { this.refInput = input }}
  />)
}

it('should render Input', () => {
  const wrapper = mount(<Component />);
  expect(wrapper.find(Input)).toHaveLength(1)
  expect(wrapper.instance().refInput).toBeTruthy();
})


来源:https://stackoverflow.com/questions/48088489/react-jestjs-enzyme-how-to-test-for-ref-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!