enzyme: wrapper.instance() is null on class component
Current behavior
wrapper.instance() and wrapper.state() are not working on a class component.
Expected behavior
wrapper.instance() and wrapper.state() work on a class component.
Your environment
I’m really confused by a component not working with instances. I have many other similar components that have a the same structure that are working. I have broken this down to a very simple component and test to show the problem.
React Component
import React from 'react';
export class EnzymeTest extends React.Component {
constructor(props) {
super(props);
this.state = {
test: true
}
}
componentDidMount() {
this.setState({test: false})
}
render() {
if (this.state.test) return <div>Test is True</div>
else return <div>Test is False</div>
}
};
Enzyme Test
import React from 'react';
import { shallow } from 'enzyme';
import { EnzymeTest } from './EnzymeTest.js';
let wrapper;
describe('isOutsideDateRange', () => {
beforeEach(() => {
wrapper = shallow(<EnzymeTest /> )
});
beforeEach(() => {
wrapper.unmount();
});
test('has state', () => {
expect(wrapper.state('test')).toBe('blah');
});
test('has a wrapper instance', () => {
expect(wrapper.instance()).toBeTruthy();
});
});
Both of the above tests fail. The state test shows this error: ShallowWrapper::state() can only be called on class components
and wrapper.instance() in null.
This is a stateful class component so I’m confused about this behavior.
API
- [ x] shallow
- mount
- render
Version
library | version |
---|---|
enzyme | 3.3 |
react | 16.3.2 |
react-dom | 16.3.2 |
react-test-renderer | 16.3.2 |
adapter (below) |
Adapter
- [x ] enzyme-adapter-react-16
- enzyme-adapter-react-16.3
- enzyme-adapter-react-16.2
- enzyme-adapter-react-16.1
- enzyme-adapter-react-15
- enzyme-adapter-react-15.4
- enzyme-adapter-react-14
- enzyme-adapter-react-13
- enzyme-adapter-react-helper
- others ( )
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 11
- Comments: 18 (9 by maintainers)
I’m not trying to test against wrapper.instance(). However, the actual component that I’m trying to test has class methods that I want to unit test, so I want to unit test them via wrapper.instance().someMethod()… bu t I can’t because wrapper.instance() returns null.
What am I doing wrong? How can I run tests against those class methods? I’m doing the same type of testing in plenty of other components so I’m confused why instance() is null in this case.
In case it helps anyone, I was experiencing a similar problem; in my case, the issue was triggered by updating react-redux to v6 or higher, and seems to have been resolved by adding an extra
.dive()
to shallow wrappers on problematic tests.Thanks @ljharb 😃