samedi 4 juillet 2020

How do I pass values from a hook into a component rendered by a test?

How do I pass values from a hook into a component rendered by a test?

Simplified example

// Here's my hook
const useThing = () => useState("I'm a thing")

// Here's where I pass the prop that I need for my test
const Parent = (props) => {
  const [thing, setThing] = useThing()

  return (
    <>
      <Stuff thing={thing} />
      <Child thing={thing} setThing={setThing} />
    </>
  )
}

// Here's where I want to test
const Child = ({ setThing }) => <button onClick={setThing} />

I want to test Child's functionality, (preferably) including useThing.

I can't pass setThing and thing as props directly to in my test, since I can't use hooks outside of react components.

Should I:

  • Test <Child /> by calling render(<Parent />), then querying to get the child, then running the tests I want? This seems like it could get kinda awkard as I refactor. Also warned against by library author.

  • Just use a mock?

  • Be reconsidering my testing approach?

  • Something else I'm not thinking of?

This is meant to be a simple stripped down example to illustrate the problem. The actual code I'm using -- it's with React Drag N Drop and an array of children. I want to make sure a child is droppable (or not) based on the right conditions. I have a mix of providers + prop drilling, and I expect to be doing a decent amount of refactoring.

That's my specific use case here, but I also want to know in general what people would recommend!

Aucun commentaire:

Enregistrer un commentaire