【问题标题】:How do I implement testing on a component with destructured props?如何对带有解构 props 的组件进行测试?
【发布时间】:2019-12-20 22:02:51
【问题描述】:

我正在尝试对使用 React 和 Material UI 构建的表单进行测试。

它在我要测试的箭头函数组件上解构了道具。我将如何解决这个问题?我尝试将 Jest 与 Enzyme 一起使用,但出现错误。

声明值的主要JS:

const Main = () => {
  const [steps, setSteps] = useState(0);
  const [values, setValues] = useState({
  one: "",
  two: "",
  three: ""
  });

组件代码:

const Component = ({
  values: { one, two, three })
})
 => {
  const checkLength =
    one.length > 0 &&
    two.length > 0 &&
    three.length > 0;

return (
    <div className="testing">
          <TextField
            label="one"
            name="one"
            placeholder="Value One"
            defaultValue={one}
            onChange={handleChange("one")}
          />
}

测试代码:

import React from 'react';
import { mount } from 'enzyme';
import Component from 'Component';

describe('Component', () => {
it('Should capture one correctly onChange', function(){
  const component = mount(<Component />);
  const input = component.find('input').at(0);
  input.instance().value = 'hello';
  input.simulate('change');
  expect(component.state().one).toEqual('hello');
});
});

我希望能够通过添加“hello”来测试输入值,看看它是否有效。我收到此错误:

TypeError: Cannot destructure property `one` of 'undefined' or 'null'.
    > 10 |   values: { one, two, three }

【问题讨论】:

    标签: javascript reactjs testing jestjs material-ui


    【解决方案1】:

    这是因为您无法解构 undefinednull 值。

    const { age } = null;
    age; // TypeError
    
    const { name } = undefined;
    name; // TypeError
    

    因此,您可以使用分配 default values(ES6) 来保护 undefined 和 null 等极端情况。

    import React from 'react'
    
    export const Component = ({ values = {} }) => {
      const { one = [], two = [], three = [] } = values
      const checkLength = one.length > 0 && two.length > 0 && three.length > 0
    
      return <div className="testing">...</div>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多