enzyme: TypeError: Attempted to wrap undefined property componentDidMount as function
Trying to test a component that fetches data in componentWillMount
, calls setState()
with the received data and renders a number of child components, like this:
export default class MyComponent extends React.Component {
constructor() {
super();
this.state = {
items: []
};
}
componentWillMount() {
Api.fetchItems().end((err, response) => {
if (response && response.ok) {
this.setState({ items: response.items });
}
});
}
render() {
return (
<div className="items-list">
{ this.state.items.map((item, i) =>
<Item item={ item } key={ i }/>
) }
</div>
);
}
}
The test is very basic and almost 1to1 taken from the example:
import sinon from 'sinon';
import { expect } from 'chai';
it('mounts correctly', () => {
sinon.spy(MyComponent.prototype, 'componentDidMount');
const wrapper = mount(<MyComponent />);
expect(MyComponent.prototype.componentDidMount.calledOnce).to.equal(true);
});
Unfortunately, the test fails:
TypeError: Attempted to wrap undefined property componentDidMount as function
at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:106:29)
at Object.spy (node_modules/sinon/lib/sinon/spy.js:41:26)
at Context.<anonymous> (MyComponent.spec.js:21:19)
Any ideas? It seems the component doesn’t even mount at all, adding a expect(wrapper.hasClass('items-list')).toBe(true)
fails as well.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 15 (6 by maintainers)
sinon
can’t stub over non-existent properties. If you add acomponentDidMount() {}
to your component, then it should work.Looks like your
<App />
is wrapped by a redux’sconnect
HOC. The prototype you’re seeing is for that. You would need to get the wrapped instanced fromConnect
or just import your component (without theconnect()
wrapper) and mock the props that redux is providing.I think
componentDidMount
is a typo and @doque was indeed referring tocomponentWillMount
, because I am getting the same error:TypeError: Attempted to wrap undefined property componentWillMount as function
.I am mounting this way:
I am testing a component wrapped in a Redux Provider and if I log the App.prototype,
componentWillMount
is simply not there:The property is not there, so
sinon
is not seeing it. Am I missing something obvious? Is this even an Enzyme issue?Just for the record, spying on other methods works just as expected: