Reputation: 2906
I'm attempting to write tests with Enzyme, but every time I pass in the setProps method, I keep getting the error: TypeError: Cannot read property 'map' of undefined. This is confusing to me, because .map is being called on the props, which from my understanding are properly defined in the setProps function below. Why am I getting this error if I have setProps defined and how can I fix it?
beforeEach(() => {
const wrapper = shallow(<Map />);
})
describe('<Map />', () => {
it('should render some stuff', () => {
wrapper.setProps({ stories: [{id: 1, title: "hello world", edit: true}] })
});
});
and the component is:
import React, { Component } from 'react';
class Map extends Component {
state = {
edit: true
}
render() {
let layout = (
<div>
{ this.props.stories.map((story, index) => {
return story.edit ?
<div key={story.id}>
<br/>
<input type="text" defaultValue={story.title} ref="stuff2" /><button name="Save" onClick={this.props.handleToggle} value={story.id}>Save</button>
<br/>
</div>
:
<div key={story.id}>
<br/>
<div ref="1">{story.title}<button key={story.id} onClick={this.props.handleToggle} value={story.id}>Edit</button><button onClick={this.props.handleDelete}>Delete</button></div>
<br/>
</div>
})}
</div>
)
return (
<div>
{layout}
</div>
);
}
}
Upvotes: 1
Views: 2431
Reputation: 5689
Please, check out how react works with enzyme, this.props.stories
will be initially undefined
because of how lifecycle works.
So before you use setProps
in your test, nothing is passed as stories
for initial rendering.
And componentWillMount, render will happen => render raises an error because you tries to iterate over undefined collection
Upvotes: 4
Reputation: 5302
Are you sure you're calling .map
on an array? props
is an object. If you're trying to map over a prop that is an array, you'll need to make sure you're targeting it correctly
Upvotes: 1