Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covering Anonymous Function Arguments in Unit Tests

I have multiple situations in code where we pass a function as an argument when creating an object (like so in onPress):

<Touchable
  onPress={() => Linking.openURL(formatUrl(url))} 
  noContainer={true}>      
    {children}
</Touchable>

When it comes down to it, this is a snippet in a larger component getting rendered. As it's not actually a method of the component, I'm not especially interested in testing it here - it will get tested as part of another component if needed. Code Coverage However, the code coverage report comes back with an indication that the function is uncovered.

Is there a way to satisfy this coverage - either by testing this function, or ignoring all functions passed in such a way (anonymously, as arguments)?

like image 507
Xianthia Avatar asked Aug 22 '26 18:08

Xianthia


1 Answers

Assuming you are using Jest, you can set your Jest mock to call the argument that it receives, so:

const componentProps = {
  onPress: jest.fn(func => func());
}

So the mocked onPress function, in this case, will receive your anonymous function and call it. Coverage will show that the anonymous function was called.

Hope it helps :)

like image 152
Aibu Avatar answered Aug 24 '26 08:08

Aibu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!