首页 > 解决方案 > 开玩笑“为了可迭代,非数组对象必须具有 [Symbol.iterator]() 方法”。

问题描述

我被 Jest 困住了,因为它告诉我向某些东西添加迭代器方法,但我不知道是什么?我在这里注意到了类似的问题,但它们大多以将某些东西包裹在一个对象中而告终。我的组件有问题吗?或者我应该以不同的方式配置 jest?

我的组件:

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames/bind';
import { Colors } from '@components/variables';
import styles from './divider.module.css';

const cx = classNames.bind(styles);

const Divider = ({
  color,
  className,
  height,
  width,
  margin,
  border,
  style,
}) => {
  const classes = cx(
    {
      divider: true,
      border,
      borderDashed: border?.dashed === true,
      borderDotted: border?.dotted === true,
    },
    color,
    className
  );

  const CustomComponent = color === 'transparent' ? 'span' : 'hr';
  return (
    <CustomComponent
      className={classes}
      style={{
        height,
        width,
        ...style,
      }}
    />
  );
};

Divider.propTypes = {
  /** Additional className for styles */
  className: PropTypes.string,
  /** The color of the divider */
  color: PropTypes.oneOf([...Colors]),
  /** The height of the divider */
  height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  /** Margin of the divider */
  margin: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.shape({}),
    PropTypes.array,
  ]),
  /** Additional inline styles */
  style: PropTypes.string,
  /** The width of the divider */
  width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  border: PropTypes.shape({ dashed: PropTypes.bool, dotted: PropTypes.bool }),
};

Divider.defaultProps = {
  color: 'transparent',
  height: '100%',
  width: 'auto',
  margin: null,
  className: null,
  style: null,
  border: null,
};

// Needed for Storybook
Divider.displayName = 'Divider';

export default Divider;

我的笑话脚本告诉我:

FAIL  src/ui/divider/divider.test.jsx
  ● Test suite failed to run

    TypeError: Invalid attempt to spread non-iterable instance.
    In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

      26 |     className
      27 |   );
    > 28 | 
         | ^
      29 |   const CustomComponent = color === 'transparent' ? 'span' : 'hr';
      30 |   return (
      31 |     <CustomComponent

      at _nonIterableSpread (src/ui/divider/index.jsx:28:39)
      at _toConsumableArray (src/ui/divider/index.jsx:26:131)
      at Object.<anonymous> (src/ui/divider/index.jsx:46:10)
      at Object.<anonymous> (src/ui/divider/divider.test.jsx:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.55 s
Ran all test suites.

Watch Usage: Press w to show more.

任何帮助或启发都会很棒!先感谢您。

标签: reactjsjestjs

解决方案


推荐阅读