【发布时间】:2019-08-13 00:56:50
【问题描述】:
我对测试 React 组件相当陌生,并且正在努力测试使用 React.createRef 创建的 ref。我已经阅读了这个很棒的回复 我不确定它是否解决了我的问题。 componentDidMount called BEFORE ref callback
constructor(props) {
super(props);
this.myRef = React.createRef();
console.log('this.myRef in constructor', this.myRef);
}
此控制台日志返回 null 并且是预期的,因为组件尚未呈现。
componentDidMount() {
console.log('this.myRef in component did mount', this.myRef);
}
return (
<div className="tab_bar">
<ul ref={this.myRef} className="tab__list direction--row" role="tablist">
{ childrenWithProps }
</ul>
</div>
控制台日志返回componentDidMount 中的ul html 元素。这也是预期的,因为组件已渲染。
然而,
当我测试这个组件时:
const children = <div> child </div>;
describe('Tab component', () => {
it('should render', () => {
const wrapper = mount(<Tab>{children}</Tab>);
const ulElement = wrapper.find('ul');
const instance = ulElement.instance().ref;
console.log('instance', instance);
expect(wrapper).toMatchSnapshot();
});
});
我的终端中的控制台日志语句(我的构造函数和 componentDidMount 中的 this.myRef)都说 {current: null} 和 instance 未定义。
谁能帮我理解发生了什么?谢谢!
【问题讨论】:
标签: reactjs unit-testing enzyme