Circular dependencies when importing sequelize

527 Views Asked by At

I have an electron project where I have a set of class extending from an abstract class. The abstract class has an import of a sequelize instance and a model (not illustrated in the reproduction code below).

When compiled, my electron app works fine. But in test, jest keeps returning the error

 Class extends value undefined is not a constructor or null

From what I read, this is caused by circular dependencies. I've been commenting over and over code around, but I am unable to understand how to prevent/resolve this issue through test.

reproduction code can be found here: https://github.com/jjoey87/jest-circular-dependencies

Is there a better way to restructure my imports or an actual workaround to have this work under jest? I don't understand why it causes no issue when compiled via electron-webpack but throws under jest. I also observe if I were to comment the imported components under module B, this allows my test to run/pass.

import ModuleC from '@common/ModuleC'
// import ComponentC from '@common/providers/ComponentC'
// import ComponentD from '@common/providers/ComponentD'
// import ComponentE from '@common/providers/ComponentE'
// import ComponentF from '@common/providers/ComponentF'
// import ComponentA from '@common/providers/ComponentA'
// import ComponentB from '@common/providers/ComponentB'

const providers = [
  // ComponentC,
  // ComponentD,
  // ComponentE,
  // ComponentF,
  // ComponentA,
  // ComponentB
]

Similarly, if I comment the import of sequelize from the Abstract class, it allows my test to pass

1

There are 1 best solutions below

0
On

First, Madge helps find the circular dependencies.

npm i --saveDev madge
node_modules/madge/bin/cli.js --warning --circular --extensions js ./

It helps identify loops that only become an issue during testing (every system handles them a bit differently). Structurally, the key would be for the model and sequelize instance to not depend on any of the commented-out components. Dependencies could be injected after construction with a factory or other more complex pattern, or contacted via loose-coupled communications like emitters.