this.refs is undefined for shallow tests using enzyme on React native

故事扮演 提交于 2019-12-07 17:09:26

问题


I have a component which has 2 input text fields.

In the componentDidMount() method I am calling this.refs.password.focus();

There is some amount of tricky business logic sitting inside my componentDidMount but while doing a shallow unit test on componentDidMount, I get error

cannot access password of undefined

I checked the instance of the shallow component and see that this.refs is undefined. My question is how can we set this through tests?

Shallow has a second parameter which we can pass called as the context where we can set the context for unit testing but it seems to be doing nothing.

Any help around this area would be highly appreciated.


回答1:


The easiest approach for this problem would be to set the refs through the instance.

const component = shallow(<Component />)
const instance = component.instance()

instance.refs = {
  password: {
    getRenderedComponent: jest.fn(() => ({
      focus: jest.fn
    }))
  }
}



回答2:


shallow does not have a ref method. You need to use mount to test the rendering in its entirety.

References: API docs: https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md

Issue: https://github.com/airbnb/enzyme/issues/316



来源:https://stackoverflow.com/questions/46480345/this-refs-is-undefined-for-shallow-tests-using-enzyme-on-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!