类型错误:无法读取未定义的属性“map”(jest.js)

Poo*_*a A 6 unit-testing reactjs jestjs

我有一个带有输入和按钮的组件。当用户在输入中键入爱好时,假设将该字符串发送到 API 进行更新。我已经设置了测试,正在测试组件是否存在,当我 console.log(component) 时,我收到错误 TypeError: Cannot read property 'map' of undefined。它说该组件未定义。

当我注释掉 {this.state.hobbies.map()} 部分(包括第二个渲染和其中的所有内容)时,该组件能够渲染。

    EditProfile.js
    import React, { Component } from 'react';
    import { MdDelete } from 'react-icons/md';
    import { updateHobbies } from '../../services/updateHobbies';
    import './edit_profile.scss';
    import PropTypes from 'prop-types';

    class EditProfile extends Component {
      state = {
        hobbies: this.props.employeeHobbies,
        userInput: ''
      };

      handleChange = e => {
        this.setState({ userInput: e.target.value });
      };

      handleButtonClick = () => {
        const hobby = this.state.hobbies.concat(this.state.userInput);
        this.setState({ hobbies: hobby, userInput: '' }, () => 
       updateHobbies(this.state.hobbies));
      };

      handleDelete = e => {
        const array = [...this.state.hobbies];
        const index = array.indexOf(e);
        if (index !== -1) {
          array.splice(index, 1);
          this.setState({ hobbies: array }, () => 
         updateHobbies(this.state.hobbies));
        }
      };

      render() {
        return (
          <div>
            <label className='employee-label'>HOBBIES: </label>
            <span>
              <input type='text' value={this.state.userInput} onChange= 
           {this.handleChange} />
              <button className='update-details-button' onClick= 
        {this.handleButtonClick}>
                Add
              </button>

              {this.state.hobbies.map(hobbies => {
                return (
                  <li className='employee-tag-list' key={hobbies}>
                    {hobbies}
                    <span className='delete-icons' onClick={() => 
         this.handleDelete(hobbies)}>
                      <MdDelete />
                    </span>
                  </li>
                );
              })}
            </span>
          </div>
        );
      }
    }
   EditProfile.propTypes = {
  employeeHobbies: PropTypes.array
};

export default EditProfile;
Run Code Online (Sandbox Code Playgroud)

EditProfile.test.js

let component;
  const chance = new Chance();
  let mockHandleChange = jest.fn();
  let mockHandleButtonClick = jest.fn();
  let mockHandleDelete = jest.fn();
  let mockUpdateHobbies;
  let mockHobbies = [chance.string(), chance.string(), chance.string()];

  function requiredProps(overrides = {}) {
    return {
      handleChange: mockHandleChange,
      handleButtonClick: mockHandleButtonClick,
      handleDelete: mockHandleDelete,
      ...overrides
    };
  }

  function renderComponent(props = requiredProps()) {
    return shallow(<Hobbies {...props} />);
  }

  beforeEach(() => {
    component = renderComponent();
  });

  it('should exist', () => {
    console.log(component.debug());
    expect(component).toHaveLength(1);
  });
Run Code Online (Sandbox Code Playgroud)

我预计测试会通过,但出现错误 TypeError: Cannot read property 'map' of undefined

Gre*_*egL 3

您可以做一些事情,所有这些都是为了解决核心问题:您没有employeeHobbies在测试中为 prop 提供值。

选择以下选项之一:

  1. 正如 @Hoyen 建议的那样,添加默认属性来指定一个空数组(employeeHobbies如果未提供)。EditProfile.defaultProps = { employeeHobbies: [] };
  2. requiredProps()测试文件的函数中,指定空数组的值employeeHobbies以及其他属性handleChange,例如handleButtonClick、 等。
  3. 初始化时state.employeeHobbies,将其设置this.props.employeeHobbies || [],为如果传递 null 或什么都没有(未定义),则它具有后备值。

我还建议您指定 as 的 proptype,employeeHobbies以便PropTypes.array.isRequired在未提供数组时获得有用的警告。这将防止组件被滥用,并违反其工作所需的合同。