score:3

Accepted answer

here's what i think is happening:

useeffect takes place after render, so when you expect mounted to be true, useeffect has not yet run. updating a ref does not trigger a re-render, so your component never updates.

the way i got this to work is by forcing an update, by calling component.setprops() before each expectation:

    it('should keep track of if a component is mounted', () => {
        let mounted;
        const component = testhook(() => {
            mounted = useiscomponentmounted();
        });
        component.setprops(); // feels a bit hacky, but it forces a re-render
        expect(mounted).tobe(true);
        component.unmount();
        component.setprops(); // this apparently even works after unmount!
        expect(mounted).tobe(false);
    });

this diagram is helpful to show when render, dom updates, useeffect, uselayouteffect, and paints happen: https://raw.githubusercontent.com/donavon/hook-flow/master/hook-flow.png


Related Query

More Query from same tag