Strange bug with Jest, create-react-app, and typescript.
Tonight Jest started failing to import my "./ProcessStore" module correctly. This module is a transitive dependency of something that my tests import.
The error I see is that the thing I import is undefined.
When I do import * as what from "./ProcessStore" and log(what), it prints all of the exports, but the values are undefined. Like {default: undefined, ResourceChange: undefined} two classes that are exported. It should be {default: <a class>, ResourceChange: <a class>}.
It's just that one file. Every other file works.
When I use npm start, it works --- this is a Jest only problem.
Also if I rename the broken file to say ./ProcessStore2, it also works.
I tried ./node_modules/jest --clearCache, which didn't help.
In case it's relevant, I'm using craco normally. Switching back to react-scripts temporarily didn't help.
I'm using react-scripts 4.0.3 (latest version).
What is going on? How do I fix this silly problem?
This was caused by a circular dependency in my project.
The circular dependency was causing Jest to return an empty module. I believe the 2nd time a module is entered, it will have undefined contents.
In my case the chain was ProcessStore.ts -> stores.ts -> ProcessStore.ts. So by the time stores.ts loads ProcessStore.ts, the process store has already been loaded, so everything is undefined.
I also ran into this issue, due to a circular dependency.
In order to confirm the nature of the bug, I console.log the missing import and executed my test. I could see that the import was in fact undefined when it shouldn't have been.
I ran this command to find circular dependencies at package/project level:
npx madge --circular --extensions ts,tsx .
This only gave me a clue as to what was going on, however.
I then used the debugger at the point where my circular dependency was occurring. Using Chrome DevTools, I inspected the call stack, and found how each import was being imported. This revealed the circular dependency very clearly. For me, this was the most important part of untangling the circular dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With