enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.95k stars 2.01k forks source link

shallow rendering: ref mock builder #721

Open charlierudolph opened 7 years ago

charlierudolph commented 7 years ago

Just an idea I had which is I believe the minimal I need in order to be to test some functionality with refs while still being able to use shallow rendering.

describe('refMockBuilder', () => {
  it('calls it for each ref with the a wrapper for the element', () => {
    const SimpleComponent = React.createClass({
      focus() {
        this.textInput.focus();
      },
      render() {
        return (
          <div>
            <input id='name' type='text' ref={(node) => { this.textInput = node; }} />
            <button onClick={this.focus}></button>
          </div>
        );
      }
    });
    mocks = {}
    const refMockBuilder = (wrapper) => {
      return mocks[wrapper.props().id] = {focus: sinon.stub()}
    }
    const wrapper = shallow(<SimpleComponent />, { refMockBuilder });
    wrapper.find('button').simulate('click')
    expect(mocks['name'].focus).to.have.been.called
  });
});

I'm happy to try and implement this if you like the idea.

ljharb commented 7 years ago

Why the id?

charlierudolph commented 7 years ago

The id is just being used as an example of a way to tell refs apart (in case you had multiple)

aweary commented 7 years ago

react-test-renderer has an API for this called createNodeMock. If we supported this, it would be nice if it was consistent with that API.

jquintozamora commented 6 years ago

Do you have any plans to support createNodeMock on enzyme mount ?