javascript - 在浅层渲染的功能组件上调用 instance() 返回 null

标签 javascript reactjs jestjs enzyme

我有以下 React 功能组件,它接受名称作为 prop

const Name = ({ name }) => <h1>{name}</h1>;

Name.propTypes = {
    name: PropTypes.string.isRequired
}

我的测试如下

describe("<Name />", () => {
    it("accepts name as a prop", () => {
        const wrapper = shallow(<Name name="Monkey D Luffy"/>);
        expect(wrapper.instance().props.name).toBe("Monkey D Luffy");
    })
})

这将返回以下错误

TypeError: Cannot read property 'props' of null

更新

我按如下方式调用名称组件

class Person extends React.Component {
  state = {name: "Name here"}
  render () {
     return  <div><Name name={this.state.name} /></div>
  }
}

我发现在无状态组件上调用 instance() 无法与 React 16 一起使用。* 在我的情况下,我无法使用 wrapper.prop()它只返回根节点的 props

为什么在渲染组件上调用实例函数时返回 null 以及如何测试传递到无状态组件的 props?

原始问题

为什么在渲染组件上调用实例函数时返回null

最佳答案

instance() === null 对于功能组件,因为功能组件没有实例。

应该使用 Enzyme 自己的 API 来访问组件属性:

expect(wrapper.prop('children')).toBe("Monkey D Luffy");

the reference解释说,

To return the props for the entire React component, use wrapper.instance().props. This is valid for stateful or stateless components in React 15.. But, wrapper.instance() will return null for stateless React component in React 16., so wrapper.instance().props will cause an error in this case.

关于javascript - 在浅层渲染的功能组件上调用 instance() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791304/

相关文章:

javascript - Chrome/Firefox 5 中的 head.js 和 jQuery 问题

javascript - react +不可变.js : merge Map into List of Maps to update state

javascript - react 。呈现和更新 1500 个 <li> 元素的简单列表时非常慢。我认为 VirtualDOM 很快

typescript - 如何期望字符串以指定的变量开头

testing - 如何使用 runSaga/redux-saga 接收拍摄

javascript - 使用 jquery 保存输入字段状态,发送到 db 稍后读取

javascript - 如何使用jquery限制用户不允许低于18岁?

javascript - React - 如果 div/span 的值更新,如何触发动画?

typescript - NestJs + TypeScript + Jest - TypeError : Class extends value undefined is not a constructor or null

javascript - AJAX 'success' 在 IE 中 AJAX 执行之前调用