How to offer good test coverage in ReactJS?

Viewed 39

Currently I've been working with ReactJS and using SonarQube to validate the quality of my code, but I've had a hard time expanding my test coverage.

I usually do unit tests based on the return that the functions produce. For example, in a Functional Component, I test the rendering of the elements and the possible events in the component (one click on a button per), but I can't test functions internal to that component, as they are encapsulated and not visible to the world outside.

const Component = () => {
  const innerFuncOne = () ={
    // logic here - how to test this?
  }

  const innerFuncTwo = () ={
    // logic here - how to test this?
  }

  return (<> Template </>)
}

I also experience this same difficulty when testing custom hooks.

const useCustomHook = () => {
  const innerFuncOne = () ={
    // logic here - how to test this?
  }

  const innerFuncTwo = () ={
    // logic here - how to test this?
  }

  return {
    innerFuncOne 
    innerFuncTwo 
  }
}

How to cover tests of these encapsulated functions? How to test them individually? I know that one possibility is to extract these options out and declare them with an export, so that they are visible in the test files, but I don't think it's a good solution.

0 Answers
Related