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

查看:23
本文介绍了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 的覆盖选项,我看到,那行

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?

推荐答案

引用附加到组件的实例,因此您必须使用 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,请添加以下行

To test for the ref, add the following line

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天全站免登陆