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:
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With