Covering Anonymous Function Arguments in Unit Tests

Viewed 800

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

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

Related