TypeError:无法读取未定义的属性“ map”(jest.js)

时间:2019-05-17 19:01:23

标签: reactjs unit-testing jestjs

我有一个具有输入和按钮的组件。当用户在输入中输入爱好时,假设将要更新的字符串发送到api。我已经设置好测试,并且正在测试组件是否存在,并且出现错误TypeError:当我console.log(component)时,无法读取未定义的属性“ map”。它说该组件是未定义的。

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

const app = next({ dev })

const handle = app.getRequestHandler()

const ssrCache = cacheableResponse({
  ttl: 1000 * 60 * 60, // 1hour
  get: async ({ req, res, pagePath, queryParams }) => ({
    data: await app.renderToHTML(req, res, pagePath, queryParams)
  }),
  send: ({ data, res }) => res.send(data)
})

server.set('trust proxy', true);

// Header security. See: https://observatory.mozilla.org/
server.use(helmet());

// Sets "Referrer-Policy: same-origin".
server.use(helmet.referrerPolicy({ policy: 'same-origin' }));

// Sets Feature-policy
server.use(helmet.featurePolicy({
    features: {
      fullscreen: ["'self'"],
      vibrate: ["'none'"],
      payment: ['https://yyy.com'],
      syncXhr: ["'self'"],
      geolocation: ["'self'"]
    }
}));

app.prepare().then(() => {
  //const server = express()

  server.get('*', function(req,res,next) {
    if(req.headers['x-forwarded-proto'] != 'https' && process.env.NODE_ENV === 'production')
    res.redirect('https://'+req.hostname+req.url)
    else
    next() /* Continue to other routes if we're not redirecting */
  });

  server.get('/', (req, res) => ssrCache({ req, res, pagePath: '/' }))

  server.get('*', (req, res) => handle(req, res))

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

EditProfile.test.js

    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;

我希望测试通过,但出现错误TypeError:无法读取未定义的属性“ map”

1 个答案:

答案 0 :(得分:0)

您可以做一些事情,所有这些目的都是为了解决核心问题:您没有在测试中提供parser.add_argument('skill', choices=skill_list, help="Which skill?", nargs='+') parser.add_argument('endpoints', default=None, help="Configuration file for the connectors as a yml file") 道具的价值。

选择以下一项:

  1. 按照@Hoyen的建议,添加默认属性以为employeeHobbies指定一个空数组(如果未提供)。 employeeHobbies
  2. 在测试文件的EditProfile.defaultProps = { employeeHobbies: [] };函数中,为requiredProps()指定一个空数组的值以及其他属性,如employeeHobbieshandleChange等。< / li>
  3. 初始化handleButtonClick时,请将其设置为state.employeeHobbies,以便在传递null或不传递任何值(未定义)时具有回退值。

我还建议您将this.props.employeeHobbies || [],的属性指定为employeeHobbies,以便在未提供数组时获得有用的警告。这样可以防止滥用该组件,并违反其需要工作的合同。