【问题标题】:Testing React Component with Jest and Enzyme. Error: Can't read property of map is undefined用 Jest 和 Enzyme 测试 React 组件。错误:无法读取地图的属性未定义
【发布时间】:2020-02-06 19:24:51
【问题描述】:

所以我无法从父组件中获取 todos,也无法自己成功设置它们。在这一点上,我并不想特别测试任何东西。只是组件“存在”而没有错误

组件代码:

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;

测试代码:

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();
    });
});

请帮忙。对 Jest 很陌生,对一般测试也很陌生。

【问题讨论】:

    标签: reactjs testing jestjs enzyme


    【解决方案1】:

    当您创建组件的浅实例时,您需要传递您正在使用的道具,而无需在组件中进行条件检查

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

    和

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

    【讨论】:

    • 感谢您的回复。是的,我相信我试过了。我的更新代码现在在上面。我之前试过这个,但我仍然收到一个“无法读取未定义的属性“地图”错误。也许我误解了你的建议。
    • 你需要的道具是todos而不是Todos
    • 不好。在我的代码中是 todos=(todos}。仍然“无法读取未定义的属性 'map'”
    • 哦,那是因为你重新创建了快照,renderer.create 你没有通过它
    • 是的,就是这样。谢谢!我也刚刚发现了这一点,但不确定这是解决问题的必要方法还是解决方法。谢谢你的帮助!
    猜你喜欢
    • 2018-10-27
    • 2019-12-24
    • 1970-01-01
    • 2017-11-09
    • 2017-12-30
    • 2021-09-20
    • 2021-05-02
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多