8
votes

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"
1
Try consoling the wrapper.state() and see if it prints out { source: true }. If that's the case, then your chai assertion is wrong. I think it should be expect(wrapper.state('sources')).to.be.true; instead.Sam R.
Thanks for your reply, @norbertpy. I managed to solve it with the answer provided by Mike Shutte below.eduardo
Glad you solved it. Then mark his answer as accepted and give him an upvote. Cheers.Sam R.

1 Answers

7
votes

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!