All imports are undefined for one module during Jest test run

Viewed 2968

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?

2 Answers

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 ran into this when I was importing in one file like this

import { myHook } from 'services/hooks/myHook'

and in another file

import { myHook } from 'services/hooks'

There was an index file

// src/services/hooks/index.ts
export * from './myHook.ts'

Converting them all to use the index path fixed it. I don't think I had a circular dependency anywhere, I never was able to truly understand what was wrong.

Related