[英]React Jest: TypeError: Cannot read property 'map' of undefined
I am new to react and have a failing test which i am not able to understand whether it's a class import issue or I am not sending required params correctly.我是新来的反应并且有一个失败的测试,我无法理解这是一个 class 导入问题还是我没有正确发送所需的参数。
Here is my code这是我的代码
import * as React from 'react'
import cx from 'classnames'
import './dropdown.scss'
export interface DropdownProps {
options: {
key: string
text: string
value: string
}[]
value?: string
placeholder?: string
onSelect?: (value: string) => any
children?: React.ReactNode
}
export const Dropdown = ({ options, value, placeholder, onSelect }: DropdownProps) => {
const hasValue = typeof value === 'string';
const [ top, setTop ] = React.useState(0);
const handleTriggerRef = (el: HTMLButtonElement) => {
if (el) {
setTop(el.clientHeight)
}
};
return (
<div className={cx('dropdown-container')}>
<button
className={cx('title', { hasValue: hasValue })}
ref={handleTriggerRef}
onClick={() => {
if (value && typeof onSelect === 'function') {
onSelect(value)
}
}}
>{hasValue ?
options.filter(item => item.value === value)[0].text :
(placeholder || 'Select value')}</button>
<div
style={{ top }}
className={cx('options')}
>
{options.map(option =>
<div
key={option.key}
className={cx('option')}
onClick={() => {
onSelect(option.value)
}}
><div className={cx('text')}>{option.text}</div></div>)}
</div>
</div>
)
};
And here is the test这是测试
import { shallow } from "enzyme/build";
import React from "react";
import { Dropdown } from "../dropdown";
describe('Dropdown component', () => {
test("Renders correctly", () => {
const wrapper = shallow(<Dropdown />);
expect(wrapper.exists()).toBe(true);
});
});
It is because you are not passing options
to your Dropdown
component.这是因为您没有将
options
传递给Dropdown
组件。
The following will prevent the error.以下将防止错误。
{options && options.map(option => .....
But what you really will also want to do in your jest test is但是你真正想要在你的笑话测试中做的是
<Dropdown options={options} />;
As you are using hooks it is recommended that we should use mount instead of shallow .当您使用钩子时,建议我们应该使用mount而不是shallow 。
The error you are getting is because props are not passed to shallow render.您得到的错误是因为道具没有传递给浅层渲染。
import { shallow } from "enzyme/build";
import React from "react";
import { Dropdown } from "../dropdown";
describe('Dropdown component', () => {
// no need to pass the optional props
const props = {
options: [{ key: 'key',text: 'text',value: 'value'}],
value: 'value',
placeholder: 'placeholder',
onSelect: jest.fn(),
children: <div>test</div>
}
test("Renders correctly", () => {
const wrapper = shallow(<Dropdown {...props}/>);
expect(wrapper.exists()).toBe(true);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.