I was testing a react functional component and the below lines which were outside the return were not getting covered

Viewed 23

This is just an example and I have all the necessary imports and all the code. The code inside the if-else blocks was not getting covered while writing test cases.

  function MyComponent() {
  const title = '';
  if (window.location.pathname === '/dashboard') {
      title= "dashboard"
  } else if (window.location.pathname === '/home') {
    title= "home"
  } else if (window.location.pathname === '/about') {
    title= "about"
   }
 return(
   <h1>{title}</h1>
 )
  
}
1 Answers

If + else if statements work in a way that if the first if statement is truthy, none of the other statements will be checked/executed. It sounds like the first if statement is always being evaluated as true. Please make sure the first if statement is not being evaluated as true when running your tests.

Related