React / JestJS / Enzyme:如何测试参考功能?

问题描述 投票:4回答:1

我正在使用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)
})

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

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

我的测试不包括在内。我需要做些什么来获得此样本组件的完整覆盖单元测试?

javascript reactjs unit-testing jestjs enzyme
1个回答
5
投票

ref附加到组件的实例,因此您将不得不使用mount来获取组件的实例。

要测试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();
})
© www.soinside.com 2019 - 2024. All rights reserved.