对于在React native上使用酶的浅层测试,this.refs是未定义的

时间:2017-09-29 01:09:00

标签: reactjs react-native jestjs enzyme

我有一个包含2个输入文本字段的组件。

componentDidMount()方法中,我呼叫this.refs.password.focus();

我的componentDidMount内部存在一些棘手的业务逻辑,但在componentDidMount进行浅层单元测试时,我收到错误

  

无法访问未定义的密码

我检查了浅组件的实例,发现this.refs 未定义 。 我的问题是我们如何通过测试来设置它?

Shallow有一个第二个参数,我们可以传递这个参数作为上下文,我们可以设置单元测试的上下文,但似乎什么也没做。

对此区域的任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:8)

解决此问题的最简单方法是通过实例设置refs

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

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

答案 1 :(得分:4)

shallow没有ref方法。您需要使用mount来完整地测试渲染。

参考文献: API文档: https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md

问题: https://github.com/airbnb/enzyme/issues/316