Enzyme: shallow rendering: ref mock builder

Created on 9 Dec 2016  路  4Comments  路  Source: enzymejs/enzyme

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.

shallow feature request

Most helpful comment

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.

All 4 comments

Why the id?

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

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.

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rexonms picture rexonms  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

timhonders picture timhonders  路  3Comments

benadamstyles picture benadamstyles  路  3Comments

AdamYahid picture AdamYahid  路  3Comments