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?

1

1 Answer 1

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

   });
   
 });
Sign up to request clarification or add additional context in comments.

8 Comments

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 <childA> 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?
In your test case what value are you providing to your props ?
I am passing an array with some static data: arr= ["node1", "node2"]
Show your complete props structure that you are having in your test case
const props = { arr: ["node1",node2"] }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.