【问题标题】:this.refs is undefined for shallow tests using enzyme on React nativethis.refs 对于在 React native 上使用酶的浅层测试未定义
【发布时间】:2018-03-10 20:36:07
【问题描述】:

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

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

在我的 componentDidMount 中存在一些棘手的业务逻辑,但是在对 componentDidMount 进行浅层单元测试时,我得到了错误

无法访问未定义的密码

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

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

我们将不胜感激有关此领域的任何帮助。

【问题讨论】:

    标签: reactjs react-native jestjs enzyme


    【解决方案1】:

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

    const component = shallow(<Component />)
    const instance = component.instance()
    
    instance.refs = {
      password: {
        getRenderedComponent: jest.fn(() => ({
          focus: jest.fn
        }))
      }
    }
    

    【讨论】:

    • 如果在组件安装过程中使用了 ref 怎么办?就我而言,当我进行初始浅层渲染时,我的测试在第 1 行失败。我什至没有机会嘲笑裁判......
    • @MegaMatt 在这种情况下,您可以将上下文作为参数传递给浅层。检查文档:github.com/airbnb/enzyme/blob/master/docs/api/shallow.md,您可以在浅层安装组件时传递 context.refs。
    • 嗨@Bajju,您能否添加一个通过上下文传递参考的示例。我有一个表格元素,并在 CDM 生命周期方法上计算高度。在这种情况下如何传递 refs!
    • @DebajitMajumder 因为你想测试 CDM ,你需要有 instance = shallow(&lt;Component {...props} /&gt;, { disableLifecycleMethods: true }) 然后添加 mock refs instance.refs = { table: { calculateHeight: mockCalculateHeight, }, };然后调用CDM(),然后验证函数。
    • instance.refs 不幸被弃用
    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 2018-11-04
      • 2021-04-24
      • 2021-06-04
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2019-02-16
      相关资源
      最近更新 更多