1
votes

How do I test a prop(callback) function that is called conditionally I have a component which passes a prop function to its child on a condition like:

if(this.props.myFun) {
  this.props.myFun();
}

to test this, I have two cases here: 1. Where the prop is passed to the component

 <ChildComp myFun={value => value } /> and I can test it from the child-
const comp = mountWithIntl(<ChildComp myFun={value => value } />);
expect(comp.instance().props.myFun).toHaveBeenCalled();
  1. Where the prop is not passed: I trying like
const comp = mountWithIntl(<MyComp />);
expect(comp.instance().props.myFun).not.toHaveBeenCalled();

But, Since If I mock the prop while mounting the component, the method will be called. But how do I test the undefined or unmocked prop? If I dont pass the prop and do:

expect(comp.instance().props.myFun).not.toHaveBeenCalled();

I will get:

jest.fn() value must be a mock function or spy

which I cant do as per my code please help

1
myFun will be undefined, so how could it possibly have been called? If you have some method inside MyComp that calls myFun, then you should test that method instead.Raicuparta
As Ricardo mentioned myFun will be undefined so you can always check: ``` expect(comp.instance().props.myFun).toBeUndefined(); ```Maciej Trojniarz
Ah! Thank you. I had to test expect(comp.instance().props.myFun).not.toHaveBeenCalled(); just it is not covered in test coverage toBeUndefined() worked for me. Thank youBenison

1 Answers

1
votes

I don't think you can test that a not passed function does not get called. What you can do to test if it is get rendered without that function. That should be enough