D. Wall
D. Wall

Reputation: 77

Testing React Component with Jest and Enzyme. Error: Can't read property of map is undefined

So i haven't been able to get the todos passed down from the parent component nor have i been able to successfully set them myself. I'm not trying to test anything in particular at this point. Just that the component 'exists' without error

Component code:

import React, { Component } from 'react';

import TodoItem from './TodoItem';

class TodoList extends Component {
    renderTodos = () => {
        const { todos } = this.props;
        return todos.map(todo => {
            return <TodoItem key={todo.id} {...todo} />;
        });
    };
    render() {
        return (
            <div>
                {this.renderTodos()}
            </div>
        );
    }
}

export default TodoList;

Test code:

import React from 'react';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';

import TodoList from './TodoList';
import TodoItem from './TodoItem';

describe(TodoList, () => {
    const todos = [
        {
            id: 1,
            text: 'Walk the walk'
        },
        {
            id: 2,
            text: 'Talk the talk'
        }
    ];
    const component = shallow(<TodoList todos={todos} />);

    it('should exist', () => {
        const component = renderer.create(<TodoList />);
        const tree = component.toJSON();
        expect(tree).toMatchSnapshot();
    });
});

Please help. New to Jest and pretty new to testing in general.

Upvotes: 0

Views: 1982

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

When you create a shallow instance of your component you need to pass the props which you are using without conditional check in your component

const component = shallow(<TodoList todos={[]}/>);

and

const component = renderer.create(<TodoList todos={[]}/>);

Upvotes: 2

Related Questions