2021-12-01

Enzyme Jest TS2722: Cannot invoke an object which is possibly 'undefined'

I'm writing a jest enzyme test where I am trying to trigger the onDismiss function.

I logged that the onDismiss exists. I am able to find the MessageBar and have logged that the onDismiss function exists.

const message_bar = tree.find(MessageBar); // This finds the message_bar we are looking for.
console.log('MMMM:', message_bar.props())
message_bar.props().onDismiss() <-- error

I've tried the following without any luck

if (message_bar.props() && message_bar.props().onDismiss()) {
   message_bar.props().onDismiss();
}
adding optional chaining "?"
In one and multiple places 
message_bar?.props()?.onDismiss()

Log output:

{
messageBarType: 1,
isMultiline: true,
onDismiss: [Function (anonymous)],
dismissButtonAriaLabel: 'Close',
ariaLabel: 'Error Details',
styles: {
  root: { marginLeft: '0%', width: '100%' },
  text: { fontSize: '14px', fontWeight: 400 }
},
className: 'errorMessage-127',
children: 'Some error occurred. Please try again'
}

Maybe I am not having the correct setup or mocking the intended function.



from Recent Questions - Stack Overflow https://ift.tt/3FZE8x9
https://ift.tt/eA8V8J

No comments:

Post a Comment