用酶测试`React.createRef` API

时间:2019-02-07 09:44:14

标签: javascript reactjs jestjs enzyme

我想测试以下使用React.createRef API的类。

尽管进行了快速搜索,但没有发现任何执行此操作的示例。有人成功吗?我将如何嘲笑裁判?

理想情况下,我想使用shallow

class Main extends React.Component<Props, State> {

  constructor(props) {
    super(props);
    this.state = {
      contentY: 0,
    };

    this.domRef = React.createRef();
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
    handleScroll();
  }

  componentWillUnmount() {
   window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = () => {
    const el = this.domRef.current;
    const contentY = el.offsetTop;
    this.setState({ contentY });
  };

  render() {
    return (
      <Wrapper innerRef={this.domRef}>
        <MainRender contentY={this.state.contentY} {...this.props} />
      </Wrapper>
    );
  }
}

更新

所以我可以使用回调ref进行测试,如下所示

 setRef = (ref) => {
   this.domRef = ref;
 }

 handleScroll = () => {
   const el = this.domRef;
   if (el) {
     const contentY = el.offsetTop;
     this.setState({ contentY });
   }
 };

 render() {
   return (
     <Wrapper ref={this.setRef}>
       <MainRender contentY={this.state.contentY} {...this.props} />
     </Wrapper>
   );
 }
}

然后测试类似

it("adds an event listener and sets currentY to offsetTop", () => {
    window.addEventListener = jest.fn();
    const component = shallow(<ScrollLis />)
    const mockRef = { offsetTop: 100 };
    component.instance().setRef(mockRef);
    component.instance().componentDidMount();
    expect(window.addEventListener).toBeCalled();
    component.update();
    const mainRender = component.find(MainRender);
    expect(mainRender.props().contentY).toBe(mockRef.offsetTop);
  }); 

1 个答案:

答案 0 :(得分:1)

没有特定的例程可以测试引用。引用只是具有current键的对象。

如果在componentDidMount的早期访问了它,则需要禁用生命周期挂钩进行测试。应该测试组件最初是否具有引用,然后才能对其进行模拟

const wrapper = shallow(<Comp/>, { disableLifecycleMethods: true });
expect(wrapper.instance().domRef).toEqual({ current: null });
wrapper.instance().domRef.current = mockRef;
wrapper.instance().componentDidMount();

由于ref作为prop传递到另一个组件,因此可以测试它是否提供了正确的ref:

expect(wrapper.find(Wrapper).dive().props().innerRef).toBe(wrapper.instance().domRef);

然后可以在Wrapper测试中测试ref current键是否分配了正确的对象。