I'm trying to reference new React 16 refs in my enzyme 3 tests so that I can call .simulate, etc on internal references.
Simplified example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
return (
<input ref={this.textInput} />
);
}
}
Test:
component = mount(<MyComponent />);
const input = component.instance().textInput.current;
input.simulate('change', { ... });
However I get errors like:
TypeError: component.instance(...).textInput.current.simulate is not a function
This is a simplified example so I'm not looking for alternate ways of finding the input - I'm curious if and how we can use and test using React 16 references?
(I wouldn't recommend using simulate anyways; it doesn't faithfully simulate anything, and it's just sugar for invoking a prop function)
As for the refs, enzyme doesn't quite support that yet, but it's coming!
Thanks @ljharb for the info, feel free to close this if you are tracking elsewhere.
I have the same problem. I've updated React to 16.4 and used React.createRef() and got an error in my tests.
enzyme: 3.3.0
enzyme-adapter-react-16: 1.1.1
Error:
TypeError: Cannot set property 'left' of undefined
198 | setTableHeadScrollLeft() {
199 | const horizontalScroll = this.tableBody && this.tableBody.scrollLeft || 0;
> 200 | this.tableHead.style.left = `-${horizontalScroll}px`;
| ^
201 | }
202 |
203 | onChangeViewRange() {
Cause of this.tableHead = React.createRef();
The .current is a DOM node or a react instance, it wouldn't have a simulate method (that's on an enzyme wrapper only).
I'm not sure there's anything actionable here.
As to @PetrivskyiTaras' issue, shallow rendering can't support refs, only mount can.