Ad

Test That React Prop Method Has Not Been Called With Jest

- 1 answer

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

Ad

Answer

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

Ad
source: stackoverflow.com
Ad