mercredi 6 novembre 2019

React Testing if Hook State was Updated by a Child Component

I've read several articles on testing React Hooks and it seems the general advice is not to directly test state. We want to be testing things that the user will actually see. In my situation I have a hook which is either true or false. This hook will determine what gets rendered in my component. Also this hook is passed as a prop to a child which is where the state change will occur.

I am looking for a way to just set the initial hook state in my test so that I don't have to go through rendering child components and context in my test just to click a button.

The parent component has the following hook and function:

export const AssignRoles = props => {
  let [openForm, setOpenForm] = useState(false);

  const handleFormOpen = (type) => { 
    setOpenForm(openForm = !openForm);
  };

return (
    <div>
      <div>
        {openForm ? <Component /> : < OtherComponent formOpen={handleFormOpen}/>}
      </div>
    </div>
  );
};

The hook openForm initially is false so the <OtherComponent> loads and takes our hook updater function as a prop.

What I want to do is write a test that checks what renders when openForm = true

I have tried a few tests like this:

it('renders <Component/>', () => {
  let openForm = true
  const wrapper = mount(<AssignRoles openForm={openForm}/>);
  expect(wrapper).toContain(<Component/>);
});

but haven't been successful.

Aucun commentaire:

Enregistrer un commentaire