代码之家  ›  专栏  ›  技术社区  ›  Tom

用酶测试“react.createref”API

  •  0
  • Tom  · 技术社区  · 7 年前

    我想测试下一个类,它使用 React.createRef 应用程序编程接口。

    不过,快速搜索并没有发现任何这样做的例子。有人成功了吗?我该怎么嘲笑裁判呢?

    理想情况下我想用 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>
        );
      }
    }
    

    更新

    所以我可以使用回调引用测试这个,如下所示

     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 回复  |  直到 7 年前
        1
  •  1
  •   Estus Flask    7 年前

    没有具体的程序来测试refs。引用只是一个对象 current 关键。

    以防它早在 componentDidMount ,需要禁用生命周期挂钩进行测试。一个组件应该测试它最初有一个引用,然后它可以被模拟。

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

    由于参考作为道具传递给另一个组件,因此可以测试它是否提供了正确的参考:

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

    然后在 Wrapper 测试可以测试 现在的 为键分配了正确的对象。