I am fairly new to testing React components and am struggling to test a ref created with React.createRef. I've read through this great response am not sure that it addresses my issue. componentDidMount called BEFORE ref callback
constructor(props) {
super(props);
this.myRef = React.createRef();
console.log('this.myRef in constructor', this.myRef);
}
This console log returns null and is expected because the component has not yet rendered.
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>
The console log returns the ul
html element in componentDidMount. This also is expected because the component has rendered.
HOWEVER,
When I am testing this component:
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();
});
});
My console log statements in my terminal (this.myRef in my constructor and in componentDidMount) both say {current: null}
and instance
is undefined.
Can anyone please help me understand what is going on? Thank you!