【问题标题】:React/JestJS/Enzyme: How to test for ref function?React/JestJS/Enzyme:如何测试 ref 函数?
【发布时间】:2018-06-13 18:48:22
【问题描述】:

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

我的测试没有涵盖。我需要做什么才能获得此示例组件的完整单元测试?

【问题讨论】:

  • 您可能必须为此使用mount

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

引用附加到组件的实例,因此您必须使用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();
})

【讨论】:

  • 如果您只想测试是否设置了实例属性,这可能就足够了。但是,如果您想使用该特定函数测试 ref 回调,它将不起作用:(请参阅reactjs.org/docs/refs-and-the-dom.html) `` function CustomTextInput(props) { return (
    ); } class Parent 扩展 React.Component { render() { return ( this.inputElement = el} /> ); } } ```
  • 问题是要全面覆盖。添加该测试可提供 100% 的覆盖率(我确实对其进行了测试)。我不明白你的评论。用答案更好地解释自己?
  • 理想情况下,您想要expect(wrapper.find(Input).ref()).eq(wrapper.instance().props.inputRef) 之类的东西,假设您正在测试将 inputRef prop 作为 ref 回调传递的功能组件。请参阅reactjs.org/docs/… 不幸的是,酶不会暴露像.ref() api 这样的东西。
  • expect(wrapper.instance().refInput).toBeInstanceOf(Input); 会更好。
【解决方案2】:

我解决了这样的问题:

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

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

【讨论】:

  • 正是我所需要的。谢谢!
猜你喜欢
  • 2018-06-12
  • 2019-02-25
  • 2018-10-31
  • 1970-01-01
  • 2018-10-20
  • 2019-02-03
  • 2019-05-12
  • 2021-01-09
  • 2018-11-01
相关资源
最近更新 更多