我是新来的反应者,并且测试不合格,我无法理解这是否是类导入问题,或者我没有正确发送所需的参数。
这是我的代码
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>
)
};
这是测试
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);
});
});
答案 0 :(得分:1)
这是因为您没有将options
传递给Dropdown
组件。
以下将防止错误。
{options && options.map(option => .....
但是在玩笑测试中您真正想要做的是
<Dropdown options={options} />;
答案 1 :(得分:1)
在使用钩子时,建议我们使用 mount 而不是 shallow 。
您得到的错误是因为道具没有传递到浅层渲染。
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);
});
});