Skip to content

Testing hooks where you return jsx #3

@gDev95

Description

@gDev95

I noticed that in your examples you always return the state variables and functions.
Example:

import { useState } from 'react';

export default () => {
  const [first, setFirst] = useState('alpha');
  const [second, setSecond] = useState('beta');
  const [third, setThird] = useState(() => 'charlie');
  const update = () => {
    setFirst(first + 'a');
    setSecond(second + 'b');
    setThird(third + 'c');
  };
  return { first, second, third, update };
};

What about if I return my jsx/view including the state. In my test it then has a problem finding the state from the hooks i wanted to test.

Example:


import { useState } from 'react';

export default () => {
  const [first, setFirst] = useState('alpha');
  const [second, setSecond] = useState('beta');
  const [third, setThird] = useState(() => 'charlie');
  const update = () => {
    setFirst(first + 'a');
    setSecond(second + 'b');
    setThird(third + 'c');
  };
  return ( 
          <h1>{first}</h1>
         <h2>{second}<h2>
         ) ;
};

Then the tests won't work

Can you help?

Edit :
Maybe it makes sense to mention my need for this. When I build a component where I am using hooks, those components are usually returning some sort of HTML right. I cannot just return the variables of the component like the state and that is it. I need to be able to test the hooks even when I return HTML

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions