How do I use refs in react native enzyme tests when mounting with jsdom?

1.2k views Asked by At

When mounting a component (using jsdom) with a child component that has a ref="nav", I expect this.refs.nav to be the child Navigator in componentDidMount. I get blank this.refs object when I console.log(this.refs) in componentDidMount.

The component below renders and works fine in the ios simulator, however refs are blank using enzyme's mount. I have also noticed that if I have a ref on the root element, that particular ref is defined in componentDidMount.

I am using:

"react": "^15.4.1",
"react-native": "^0.39.2",
"chai": "^3.5.0",
"enzyme": "^2.7.0",
"jsdom": "^9.9.1",
"mocha": "^3.2.0",
"react-native-mock": "^0.2.9"

setup.js runs before all tests

var jsdom = require('jsdom').jsdom;
global.__DEV__ = true;
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    global[property] = document.defaultView[property];
  }
});
global.navigator = {
  userAgent: 'node.js'
};
require("react-native-mock/mock");

TEST

describe("MyComponent", function() {
  it("does a thing", function() {
    const view = mount(<MyComponent/>);
    expect(...);
  });
});

COMPONENT

const routes = [
  {id: "location", index: 0},
  {id: "rate", index: 1},
  {id: "genres", index: 2},
  {id: "availabilities", index: 3}
];

class MyComponent extends React.Component {
  componentDidMount() {
    console.log(this.refs); // {}
  }

  renderScene() {
    return return <Button ref="test" title="Hello" onPress={() => { } } />;
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Navigator
          ref="nav"
          renderScene={this.renderScene}
          initialRouteStack={routes}
          sceneStyle={{ flex: 1 }}
          configureScene={() => Object.assign(Navigator.SceneConfigs.HorizontalSwipeJump, { gestures: {} })}
        />
        <TouchableHighlight ref="prev" key="prev" onPress={this.handlePressPrev}>
          <Text>Prev</Text>
        </TouchableHighlight>
        <TouchableHighlight ref ="next" key="next" onPress={this.handlePressNext}>
          <Text>Next</Text>
        </TouchableHighlight>
      </View>
    );
  }

}
1

There are 1 answers

8
Codesingh On

this.refs is blank because ref belongs to the navigator component which is not rendered which is not rendered.

You might have noticed the ShallowRenderer doesn't have docs for a ref() method, while the MounedRenderer does. If you want to test refs you have to mount.

In case of navigator component you need to give ref parameter to every component in renderscene() function.