我想测试以下使用React.createRefapi的类。
React.createRef
快速搜索没有发现任何执行此操作的示例。有人成功吗?我将如何嘲笑裁判?
理想情况下,我想使用shallow。
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); });
没有特定的例程可以测试参考。引用只是带有current键的对象。
current
如果它是在早期访问的componentDidMount,则需要禁用生命周期挂钩进行测试。应该测试组件最初是否具有引用,然后可以对其进行模拟
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键分配了正确的对象。
Wrapper