0

I have a functional component which uses useState hook as shown below:

import React,{useState} from 'react';
    export const PList = (props) =>{
      const [obj, setObj]= useState({
        value: null,
       open: null
      });
      let onDeleteList = (data) =>{
        setObj({....});
      };
      return(
        <React.Fragment>
            { 
                props.arr.map((p,i)=>{
                    return <childA onDeleteList={onDeleteList} />
                })
            }
         </React.Fragment>
      );
    }

I an using Jest+ enzyme and looking to write a test case to test the onDeleteList function in this component. I have tried with the below code:

describe('PList',()=>{
   let wrapper = shallow(<Plist {...props}/>);
   it('should call onDeleteList',()=>{
      expect(wrapper.find('onDeleteList')).toBeTruthy();
   });
 });

I am not sure if this is the correct way, the coverage report still shows the onDeleteList() is not covered in the test case. Can anyone please advise how can I write a test case for this scenario?

user1122
  • 47
  • 1
  • 6
  • Does this answer your question? [Testing React Functional Component with Hooks using Jest](https://stackoverflow.com/questions/54713644/testing-react-functional-component-with-hooks-using-jest) – acesmndr Jan 09 '21 at 06:00

1 Answers1

1

This is how you should be testing:

import childA here 

describe('PList',()=>{
   let wrapper = shallow(<Plist {...props}/>);
   it('should call onDeleteList',()=>{
      const onDeleteListHandler=wrapper.find(childA).at(0).prop("onDeleteList");
    onDeleteListhandler(pass your data here);
     expect(onDeleteListhandler).toHaveBeenCalledTimes(1);
    

   });
   
 });
Sakshi
  • 1,464
  • 2
  • 8
  • 15
  • Thank you Sakshi..! But when I ran this code it had thrown an error on the wrapper,find statement at 'prop' saying "Method props is meant to run on 1 node. 0 found instead. Probably, this is because the is being returned from an arr.map(). Sorry I missed that, I have now updated the code in the question. Can you please advise further? – user1122 Jan 09 '21 at 05:55
  • In your test case what value are you providing to your `props` ? – Sakshi Jan 09 '21 at 06:45
  • I am passing an array with some static data: arr= ["node1", "node2"] – user1122 Jan 09 '21 at 07:15
  • Show your complete props structure that you are having in your test case – Sakshi Jan 09 '21 at 07:52
  • const props = { arr: ["node1",node2"] } – user1122 Jan 09 '21 at 07:57
  • it should be like this: const props={arr:["node1","node2"]} – Sakshi Jan 09 '21 at 08:01
  • Yes, I did pass the props as above – user1122 Jan 09 '21 at 08:06
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227072/discussion-between-sakshi-and-raghu). – Sakshi Jan 09 '21 at 08:07