javascript React/JestJS/Enzyme:如何测试 ref 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48088489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:47:29  来源:igfitidea点击:

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

javascriptreactjsunit-testingjestjsenzyme

提问by user3142695

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

我正在使用 Jest 和 Enzyme 为这个非常简单的组件运行单元测试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

我也在使用 Jest 的覆盖选项,我看到,那条线

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?

不在我的测试范围内。我必须做什么才能获得此示例组件的完整单元测试?

回答by Yangshun Tay

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

ref 附加到组件的实例,因此您必须使用它mount来获取组件的实例。

To test for the ref, add the following line

要测试ref,请添加以下行

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();
})