У меня есть компонент, который имеет вход и кнопку. Когда пользователь вводит хобби во ввод, предполагается, что эта строка будет обновлена в API. Я настроил свой тест, и я проверяю, существует ли компонент, и я получаю ошибку TypeError: Невозможно прочитать свойство 'map' undefined, когда я console.log (component). Это говорит о том, что компонент не определен.
Когда я закомментирую раздел {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;
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);
});
Я ожидал, что тест пройден, но я получаю сообщение об ошибке, TypeError: Невозможно прочитать свойство 'map' из неопределенного