vendredi 11 décembre 2020

Test onChange function passing in input search field through props.. the error im getting is TypeError:Cannot read property 'child' of undefined

this is how my autocomplete component looks like. im actually passing object array of options.

const AutoComplete = ({ options }) => {
const [activeOption, setActiveOption] = useState(0);
const [filteredOptions, setFilteredOptions] = useState([]);
const [showOptions, setShowOptions] = useState(false);
const [userInput, setUserInput] = useState("");

this is my onChange function looks like:

const onChange = (e) => {
//Change(e, options, setActiveOption, setFilteredOptions, setShowOptions, setUserInput);
console.log(e);
const userInput = e.currentTarget.value;

const filteredOptions = options.filter((optionName) =>
  optionName.fruitName.toLowerCase().includes(userInput.toLowerCase())
);
setActiveOption(0);
setFilteredOptions(filteredOptions);
setShowOptions(true);
setUserInput(e.currentTarget.value);
};

this is how my return method looks like:

return (
<React.Fragment>
  <div ref={node} onClick={handleClick}>
    <div className="search">
      <input
        ref = 'pollname'
        type="search"
        className="searchBox"
        placeholder="Fruit Name"
        onChange={onChange}
        onKeyDown={onKeyDown}
        value={userInput}
      />
    </div>
    {debouncedVal}
    {/* {optionList} */}
  </div>
 </React.Fragment>
 );

this is how my test case look like, what im trying to test here is when i trigger onchange change in input field it should be called once:

describe('onChange', () => {
let options=[
  {
    fruitName: 'Papaya',
    img:'https://c.ndtvimg.com/2019-06/qlo3s8ko_papaya-seeds_625x300_06_June_19.jpg' 
  },
  {
    fruitName: 'Apple',
    img: 'https://www.dukachapchap.co.ke/wp-content/uploads/2019/01/APPLE.jpg'
  },
  {
    fruitName: 'Banana',
    img: 'https://images.immediate.co.uk/production/volatile/sites/30/2017/01/Bananas-218094b- 
    scaled.jpg?quality=90&resize=960%2C872'
  },
  {
    fruitName: 'Peach',
    img: 'https://d.newsweek.com/en/full/1625852/peach.jpg? 
    w=1600&h=1200&q=88&f=af0637f100a4664ffd0e2a4158607f21'
  }
]

it("responds to change in input field", ()=> {
  const event = {currentTarget: {value: "pap"}};
  const wrapper = mount(<AutoComplete options={options}></AutoComplete>)
  const handleChangeSpy = jest.spyOn(wrapper.instance(), 'onChange');
  wrapper.update();
  wrapper.instance().forceUpdate();
  const change = wrapper.find('input').props('onChange');
  change.ref('pollName').simulate('change', event);
  expect(handleChangeSpy).toHaveBeenCalledTimes(1);
})

Aucun commentaire:

Enregistrer un commentaire