enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.95k stars 2.01k forks source link

TypeError: Cannot read property 'current' of undefined #2539

Closed coclauso closed 3 years ago

coclauso commented 3 years ago

Current behavior

mount() fails with TypeError: Cannot read property 'current' of undefined. Note that this is similar to #2004 , but no causes described there seem to apply.

In this case, it seems to be triggered by a specific combination of lazy component and useState:

describe('describe', () => {
    it('test', () => {
        const wrapper = mount(
        <React.Suspense fallback={<div>loading</div>}>
            <Component />
        </React.Suspense>
        );
    });
});

function Component() {
    const [alreadyRun, setAlreadyRun] = React.useState(false);

    React.useEffect(() => {
        setAlreadyRun(true);
    }, []);

    const Component2 = React.lazy(() => {
        return Promise.resolve({ default: () => <div></div> });
    });

    if (!alreadyRun) {
        return null;
    }

    return <Component2 />;
}

Zipfile with fully working repro project is attached: repro-enzyme-issue.zip

Expected behavior

Test doesn't fail with this error.

Your environment

nodejs v14.17.3

API

Version

library version
enzyme 3.11.0
react 16.14.0
react-dom 16.14.0
react-test-renderer 16.14.0
adapter (below) 1.15.6

Adapter

ljharb commented 3 years ago

@coclauso i'm very confused - you should never define one component inside another. What happens if you hoist Component2 outside of Component?

ljharb commented 3 years ago

nvm, that's a red herring (but seriously, hoist that component out) - i've reproduced the problem.