我想测试以下使用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);
});