如何在具有解构道具的组件上实现测试?



我正在尝试在我使用 React with Material UI 构建的表单上实现测试。

它在我想测试的箭头函数组件上具有解构的道具。我将如何解决这个问题?我试过将Jest与酶一起使用,但我得到错误。

用于声明值的主 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 }

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

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

因此,您可以使用分配默认值 (ES6(来保护未定义和空等极端情况。

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>
}

最新更新