Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using React 16 createRef #1704

Closed
Tracked by #1553
gthomas-appfolio opened this issue Jul 4, 2018 · 4 comments
Closed
Tracked by #1553

Using React 16 createRef #1704

gthomas-appfolio opened this issue Jul 4, 2018 · 4 comments

Comments

@gthomas-appfolio
Copy link

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?

@ljharb
Copy link
Member

ljharb commented Jul 4, 2018

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

@gthomas-appfolio
Copy link
Author

Thanks @ljharb for the info, feel free to close this if you are tracking elsewhere.

@PetrivskyiTaras
Copy link

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();

@ljharb
Copy link
Member

ljharb commented Aug 15, 2018

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.

@ljharb ljharb closed this as completed in d8a45b9 Aug 15, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants