我想测试以下类,该类使用
快速搜索没有显示任何这样的示例。有人成功过吗?我该如何模拟引用?
理想情况下,我想使用
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>
);
}
}
更新
我可以使用回调引用来测试这个,具体如下:
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);
});
const ref = { current: null }; const wrapperWrapper = shallow(<Wrapper innerRef={ref}; expect(ref.current).toBe(wrapperWrapper.instance())
。我不确定offsetTop在哪里涉及到了。 - Estus Flaskthis.domRef.current
引用 DOM 节点,因此可以访问其所有属性,其中我使用了offsetTop
。我想要的是如何模拟由React.createRef()
设置的 DOM 节点。 - TomReact.createRef
API 来实现这一点 :) - Tom{current: null}
对象。如果您想使用真正的DOM引用,那么我建议不要在Enzyme单元测试中这样做。 - Estus Flask