lundi 14 octobre 2019

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.

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

Aucun commentaire:

Enregistrer un commentaire