Afsar
Afsar

Reputation: 3124

Jest: functional component array list not mapping after adding element

I am trying to list person by clicking onClick function to add empty object so that map can loop over and show div. I see prop onclick function calling works but i map is not looping over it.

a little help would be appreciated.

// functional component

    const listing = ({list=[]}) => (
    <>
        {
        <div id='addPerson'  onClick={() => list.push({})}>Add person</div>}

        {list.map((element, index) => (
        <div key={index} className='listItems'>
            <p>list name</p>            
        </div>
        ))}
    </>
    );

    export default listing;

// test case

it('renders list-items', () => {
 const wrapper = shallow(<listing />);
 wrapper.find('#addPerson').prop('onClick')();
 console.log(wrapper.find('.listItems').length); // showing zero, expected 1
});


Upvotes: 0

Views: 268

Answers (1)

Abhishek Jain
Abhishek Jain

Reputation: 2977

Updating List is not going to cause a re-render in your component. I am not sure where List is coming from, but I am assuming it is coming from a local state in the parent, or probably redux store. From inside your component, you will have to call a function in your parent to update the list array there.

Below is a version of your component, assuming the list in your local state. You will have to adjust the code to update the state in the parent or redux store, but the below should be enough to give you an idea of what to do. Also, don't push the element to array, as it mutates the object and will not contact re-render.

const Listing = ({list = [], addToList}) => {
  return <>
    {
      <div id='addPerson' onClick={() => addToList({})}>Add person</div>}

    {list.map((element, index) => (
      <div key={index} className='listItems'>
        <p>list name</p>
      </div>
    ))}
  </>
};

Upvotes: 1

Related Questions