1
const Avatar = (props) => {
  const [hovered, setHovered] = useState('');
  return (
    <div className="user-avatar-wrapper">
      <div
        className="placeholder"
        onClick={() => {
          setHovered(true);
        }}
      />
    </div>
  )
}

How do I test if hovered got changed after simulating click on ".placeholder"?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Luis Felipe Perez
  • 339
  • 1
  • 4
  • 18
  • 2
    This is generally discouraged, here's a good explanation why: https://stackoverflow.com/questions/55342181/set-state-when-testing-functional-component-with-usestate-hook Once you use the value of `hovered` to render something different (e.g. a different text / apply a different class), you could verify that... – forrert Jul 04 '19 at 20:41
  • In addition, of @forrert comment, Enzyme doesn't support hooks yet anyway. According to [this issue](https://github.com/airbnb/enzyme/issues/2011) partial support was merged but not yet released. – colinux Jul 04 '19 at 20:44
  • Yeah. That's make sense. In my case, I use hovered to add a class in another place. So based on what you guys are saying, i should now verify if the class is there, right? – Luis Felipe Perez Jul 04 '19 at 21:11

1 Answers1

1

According to @forret and @colinux I should not test the state variation, but the reaction of that state change.

That was the full code:

const Avatar = (props) => {
  const [hovered, setHovered] = useState('');
  return (
    <div className="user-avatar-wrapper">
      <div
        className="placeholder"
        onClick={() => {
          setHovered(true);
        }}
      />
     {hovered &&
      <div className="my-hidden-element">
        ...something
      </div>
     }
    </div>
  )
}

Then instead of testing "hovered", I should test if .my-hidden-element is now being rendered.

Luis Felipe Perez
  • 339
  • 1
  • 4
  • 18