preactjs / preset-vite

Preset for using Preact with the vite bundler
https://npm.im/@preact/preset-vite
MIT License
262 stars 26 forks source link

TypeError: Cannot read properties of null (reading 'useContext') #124

Closed dolie closed 5 months ago

dolie commented 5 months ago

Describe the bug Hello,

I'm not able to run Preact components using SWR, in a test environnement. In dev/prod environnement Preact handles perfectly SWR, but not in test environnement. When I launch the test, it returns the error : TypeError: Cannot read properties of null (reading 'useContext')

To Reproduce

Barebone example : https://github.com/dolie/preact-swr-vitest-bug

Steps to reproduce the behavior:

  1. git clone git@github.com:dolie/preact-swr-vitest-bug.git
  2. pnpm i
  3. pnpm vitest

Expected behavior Preact handles SWR in a test environnement, as it is running in dev/prod environnement.

Additional Context

SWR Vitest MSW Testing-library

339088817-e5442f68-71b5-4754-bb6f-2daf198164ec-2
JoviDeCroock commented 5 months ago

As your stacktrace sugggests this error is happening in react.development.js which means that you are trying to import useContext from React rather than Preact. I don't think this bug belongs here, it might be due to preset vite but def not on the core repo

rschristian commented 5 months ago

Vitest unfortunately has problems aliasing, this is something we've seen a few times. For reference, https://github.com/vitest-dev/vitest/issues/5004, https://github.com/vitest-dev/vitest/issues/4365#issuecomment-1955992821, potentially https://github.com/vitest-dev/vitest/issues/1910

I think this is something Vitest needs to address, not us here.

dolie commented 5 months ago

Thank you for you fast answer !

Ok, so I added preact/compat using pnpm aliases, but it throws a new error about useSyncExternalStore ?

Capture d’écran 2024-06-17 à 17 26 06
rschristian commented 5 months ago

That error says you're loading multiple copies of Preact at once; hooks, in both Preact and React, require that the library is loaded as singleton (only once).

Probably the dual-package hazard: https://github.com/vitest-dev/vitest/issues/4365. Again, something that unfortunately needs to be addressed in Vitest (as far as I am aware).

dolie commented 5 months ago

Vitest team found a workaround😉 I updated the repo with it. Thank you for your help @rschristian @JoviDeCroock 🙏