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

use*_*695 6 javascript unit-testing reactjs jestjs enzyme

我正在使用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)
})
Run Code Online (Sandbox Code Playgroud)

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

ref={input => { this.refInput = input }}
Run Code Online (Sandbox Code Playgroud)

我的考试不包括在内。我需要怎么做才能获得此样本组件的完整单元测试?

Yan*_*Tay 7

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

要测试ref,请添加以下行

expect(wrapper.instance().refInput).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

最后结果:

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();
})
Run Code Online (Sandbox Code Playgroud)

  • 理想情况下,假设您正在测试正在将inputRef属性作为ref回调传递的功能组件,则您需要`expect(wrapper.find(Input).ref())。eq(wrapper.instance()。props.inputRef)`之类的东西。参见https://reactjs.org/docs/refs-and-the-dom.html#exposed-dom-refs-to-parent-components不幸的是,酶没有公开类似.ref()API的东西。 (4认同)

小智 7

我这样解决了这个问题:

const ref = React.createRef();
const props = { register: jest.fn(params => ref), label: "label text", ...params };
let wrapper = mount(
    <ThemeProvider theme={theme}>
        <Input {...props} />
    </ThemeProvider>
);
expect(wrapper.find(Entity).getElement().ref).toBe(ref);
Run Code Online (Sandbox Code Playgroud)

我在输入内部有实体组件,它接收 ref 函数。