开玩笑的错误:TypeError:无法读取未定义的属性“选项”

时间:2019-01-16 18:42:06

标签: javascript reactjs unit-testing ecmascript-6 jestjs

在测试此组件时出现此错误:

import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import TableItemsHeaders from './TableItemsHeaders';

const TableItemsHeader = ({ t }) => {
  const tableItemsHeaders = TableItemsHeaders(t);

  return (
    <div className="row header">
      {tableItemsHeaders.map(itemsHeaders => (
        <div className="cell" key={itemsHeaders.key}>
          {itemsHeaders.header}
        </div>
      ))}
    </div>
  );
};

TableItemsHeader.propTypes = {
  t: PropTypes.func.isRequired,
};

export default translate()(TableItemsHeader);

我在测试中所拥有的就是:

import React from 'react';
import { shallow } from 'enzyme';
import TableItemsHeader from '../../TableItemsHeader';

describe('The Shipments/TableItemsHeaders component', () => {
  let props;

  beforeEach(() => {
    props = {
      t: k => k,
    };
  });

  it('renders TableItemsHeader)', () => {
    const wrapper = shallow(<TableItemsHeader {...props} />);

    expect(wrapper.length).toEqual(1);

    console.log(wrapper.debug());
  });
});

这是错误:

 FAIL  src/client/pages/Shipments/__tests__/components/TableItemsHeader-test.js
  The Shipments/TableItemsHeaders component
    ✕ renders TableItemsHeader) (12ms)

  ● The Shipments/TableItemsHeaders component › renders TableItemsHeader)

    TypeError: Cannot read property 'options' of undefined

      13 | 
      14 |   it('renders TableItemsHeader)', () => {
    > 15 |     const wrapper = shallow(<TableItemsHeader {...props} />);
         |                     ^
      16 | 
      17 |     const componentInstance = wrapper.instance();
      18 | 

at new Translate (node_modules/react-i18next/dist/commonjs/translate.js:63:135)

1 个答案:

答案 0 :(得分:2)

该错误与react-i18next在测试环境中配置不正确有关。 translate()包装了您的组件,并且在您的测试环境中不在其提供程序上下文中。要模拟该库,您可以在这里查看:https://react.i18next.com/misc/testing。但是,我觉得模拟很烦人,并且由于您没有测试其功能,所以通常只看包装 像这样的组件:

const wrapper = shallow(<TableItemsHeader.WrappedComponent {...props} />);