Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling instance() on shallow rendered functional component returns null

I have following React functional component which accepts name as a prop

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

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

And my test is as follows

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

This returns following error

TypeError: Cannot read property 'props' of null

Update

I am calling the Name component as follows

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

I found out that calling instance() on a stateless component not gonna work with react 16.* I can not use wrapper.prop() in my case as it only returns the props of the root node

Why does it return null when calling instance function on the rendered component and how do I test props passed into a stateless component?

Original Question

Why does it return null when calling instance function on the rendered component

like image 322
It worked yesterday. Avatar asked Dec 15 '18 09:12

It worked yesterday.


1 Answers

instance() === null for functional component because functional components don't have instances.

Enzyme's own API should be used to access component props:

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

As the reference explains,

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.

like image 181
Estus Flask Avatar answered Sep 30 '22 01:09

Estus Flask