Enzyme: "TypeError: Cannot read property 'state' of undefined" in shallow render

Created on 9 Mar 2018  路  9Comments  路  Source: enzymejs/enzyme

I have those two files:

// ShowName.js
class ShowName extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: 'Lorem'
    }
  }

  render() {
    return (
      <div>
        {this.state.name}
      </div>
    )
  }
}
// ShowName.test.js
describe('ShowName', () => {
  const wrapper = shallow(<ShowName />)
  console.log(wrapper.state())
})

But when I run the tests the message that i got is: TypeError: Cannot read property 'state' of undefined. When I type console.log(wrapper) the printed message shows that wrapper is not undefined, but a just fine shallow rendered component, with props, length, etc...

If i use mount this works fine.

So, I would like to know why this TypeError message is showing up instead of giving me the component's state.

Plus: When i try wrapper.instance() i get just undefined as answer.

API

  • [x] shallow
  • [ ] mount
  • [ ] render

Version

| library | version
| ---------------- | -------
| Enzyme | 2.9.1
| React | 15.6.2

Most helpful comment

(Separately, you don鈥檛 want to create wrappers in a describe; only in an it)

I鈥檇 be very surprised if merely importing react-test-renderer broke things, however, with enzyme, you definitely shouldn鈥檛 ever need that package.

Closing since this seems resolved.

All 9 comments

Is it a typo?

//  const wrapper = shallow(<Sample />)
const wrapper = shallow(<ShowName />)

After I renamed the component name, I can get the following result from console.log(wrapper.state())

{ name: 'Lorem' }

@koba04 yes, was a typo in the issue description. Thank you for the alert!

And I still cant get the state :/

@kaueburiti I can't reproduce this. Can you create a repository to reproduce this?

@koba04 hey man, I just solve the problem!

The only thing that I did was remove the react-test-renderer from my packages. This package was used in tests non related with this one that I reported above.

This action solve the problem, but I have no ideia about how react-test-renderer affected all tests. I dont really know.

And yes, I'm pretty sure that the only thing that I did to solve the problem was remove react-test-renderer. This may be worthy of research.

(Separately, you don鈥檛 want to create wrappers in a describe; only in an it)

I鈥檇 be very surprised if merely importing react-test-renderer broke things, however, with enzyme, you definitely shouldn鈥檛 ever need that package.

Closing since this seems resolved.

Untitled

TypeError: Cannot read property 'state' of undefined

@jzebgul please file a new issue.

@jzebgul please file a new issue.

can you help me what should i do to pass the test

File a new issue, so we can discuss it without bothering all the people subscribed to this one.

Was this page helpful?
0 / 5 - 0 ratings