javascript - react Jest : TypeError: Cannot read property 'map' of undefined

标签 javascript reactjs testing jestjs

我是新手,有一个失败的测试,我无法理解这是一个类导入问题,还是我没有正确发送所需的参数。

这是我的代码

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

最佳答案

这是因为您没有将 options 传递给您的 Dropdown 组件。

以下将防止错误。

{options && options.map(option => .....

但是在 Jest 测试中你真正想要做的是

<Dropdown options={options} />;

关于javascript - react Jest : TypeError: Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58373850/

相关文章:

javascript - 请解释一下这段代码

javascript - 在 ES6 中追加对象?

node.js - 在 axios.delete() 上获取 404(未找到)

php - mock 重载类缺少方法

python - 访问用补丁模拟的对象

javascript - AngularJS 显示元素(如果它在数组中)

javascript - 变量未定义而已定义

javascript - Angular - 根据传入的变量更改组件/指令的大小

javascript - map函数中setState的使用方法

php - 在 localhost 中执行跨浏览器测试的应用程序工具