React / JestJS / Enzyme:如何测试ref函数? [英] React/JestJS/Enzyme: How to test for ref function?

查看:310
本文介绍了React / JestJS / Enzyme:如何测试ref函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jest和Enzyme对该简单组件 render()进行单元测试:

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

我也在使用Jest的coverage选项,在那里,我看到

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

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

我的测试未涵盖。

推荐答案

该引用附加到实例,我该怎么做才能获得对该示例组件的完整的单元测试?组件,因此您必须使用 mount 获取组件实例。

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

要测试 ref ,请添加

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

最终结果:

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

这篇关于React / JestJS / Enzyme:如何测试ref函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆