pmndrs / use-cannon

👋💣 physics based hooks for @react-three/fiber
https://cannon.pmnd.rs
2.73k stars 153 forks source link

Jest cannot find module '@react-three/cannon' #419

Open dmnkb opened 1 year ago

dmnkb commented 1 year ago

Although I'm not perfectly sure if this is more of a jest issue than a cannon one, I'd like to try to start here. When writing a unit test covering cases in a file that imports cannon, all tests fail due to not being able to find the module '@react-three/cannon'. What's strange about this, is, that this is the only module jest is having problems with. For instance, fiber and postprocessing are working perfectly fine. Maybe there is a way to resolve this issue. Please see the screenshot for reference and thank you in advance!

image

tedsecretsource commented 1 year ago

I'm having the same problem in both Jest and Vitest

image
isaac-mason commented 1 year ago

This could be caused by @react-three/cannon only being distributed as esm / not having a main defined in package.json? I'll try and find some time to look into.

Jest by default only supports cjs. I'm not sure about vitest. If that's the case, @react-three/cannon and @pmndrs/cannon-worker-api could have a cjs distribution for better compatibility.

Jest does have experimental support for esm that could help: https://jestjs.io/docs/ecmascript-modules


It's worth noting though that @react-three/cannon runs cannon-es inside a web worker. Many test environments, e.g. regular jsdom, don't support web workers. There are some libraries out there that may solve this (e.g. https://github.com/developit/jsdom-worker#readme, from a quick search), but I don't have any experience with them and can't comment on whether they'll work for @react-three/cannon.

tedsecretsource commented 1 year ago

Thanks for the background, very helpful! Note that we're not hoping to test @react-three/cannon itself but rather test other components that have a @react-three/cannon dependency. Based on what you said, @isaac-mason, it sounds like maybe the solution is to mock @react-three/cannon?

vinod-luminar commented 4 months ago

Hi @tedsecretsource, Are able to test components with @react-three/cannon . It will be helpful for me if you can share your approach. Thanks.