Enzyme: Using React 16 createRef

Created on 4 Jul 2018  路  4Comments  路  Source: enzymejs/enzyme

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?

package 16

All 4 comments

(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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thurt picture thurt  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

abe903 picture abe903  路  3Comments

potapovDim picture potapovDim  路  3Comments

blainekasten picture blainekasten  路  3Comments