Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme wrapper.state returns null

I'm trying to check the default state of my component in my Enzyme unit tests. For this, I have the following component:

import React, { Component } from 'react';

class Picker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sources: true
        };
    }
}

...

export default Picker;

Finally, my unit test looks like this:

it('should contain `everything` as a default value', () => {
  const wrapper = mount(<Picker name='cnn' />);
  expect(wrapper.state('sources')).to.exist()
});

The problem I'm facing here is that, I'm unable to get the component default state. The function wrapper.state('sources') should be returning 'true' if I'm not wrong.

Is there any other step I'm missing? I'm using:

  • "react": "^16.2.0"
  • "chai": "^4.1.2",
  • "enzyme": "^3.2.0",
  • "enzyme-adapter-react-16": "^1.1.1",
  • "jsdom": "^11.5.1",
  • "mocha": "^4.0.1",
  • "react-addons-test-utils": "^15.6.2"
like image 735
eduardo Avatar asked Dec 28 '17 16:12

eduardo


People also ask

What is wrapper instance ()?

instance() => ReactComponent. Returns the single-node wrapper's node's underlying class instance; this in its methods. It must be a single-node wrapper. NOTE: With React 16 and above, instance() returns null for stateless functional components.

How do enzymes access the state?

Now, our component is rendered and we can access props/state/methods using wrapper . Here is how you can access them: import {shallow} from 'enzyme'; describe('SomeComponent component', () => { it('Shallow rendering', () => { const wrapper = shallow(<SomeComponent someProp={1}/>); const componentInstance = wrapper.


1 Answers

I've wrestled with this a lot! Since Picker is a subclass of Component, the state you are looking for actually exists on wrapper.instance(), not the wrapper.

The "wrapper" return value of shallow and mount is just that: a wrapper. It's not the actual component you're trying to test. I think of it as a little environment that the component is surrounded by.

To make assertion on state, props, and functions on a component, I have better success reaching for:

const component = wrapper.instance()

Then on component, you can call .state, .props, &c.

Let me know if you have any questions!

like image 169
tmikeschu Avatar answered Nov 05 '22 00:11

tmikeschu