对于React Native上使用酶的浅层测试,this.refs是未定义的 [英] this.refs is undefined for shallow tests using enzyme on React native

查看:199
本文介绍了对于React Native上使用酶的浅层测试,this.refs是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a component which has 2 input text fields.

componentDidMount()方法中,我调用this.refs.password.focus();

componentDidMount内部有一些棘手的业务逻辑,但是在componentDidMount上进行浅层单元测试时,出现错误

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

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

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有第二个参数,我们可以将其传递为上下文,我们可以在其中设置用于单元测试的上下文,但这似乎无济于事.

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.

推荐答案

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

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
    }))
  }
}

这篇关于对于React Native上使用酶的浅层测试,this.refs是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆