angularjestjsangular9

Error running Jest tests after upgrading to Angular 9: TypeError: Cannot read property 'ngModule' of undefined


I upgraded from Angular 8.2 to Angular 9. My project is working as expected, as is the build however many of the tests are failing with this error:

TypeError: Cannot read property 'ngModule' of undefined

  at isModuleWithProviders (../packages/core/src/render3/jit/module.ts:530:37)
  at expandModuleWithProviders (../packages/core/src/render3/jit/module.ts:523:7)
      at Array.map (<anonymous>)
  at Function.get (../packages/core/src/render3/jit/module.ts:127:29)
  at getNgModuleDef (../packages/core/src/render3/definition.ts:761:27)
  at isNgModule (../packages/core/src/render3/jit/module.ts:534:12)
  at ../packages/core/src/render3/jit/module.ts:464:10
      at Array.forEach (<anonymous>)
  at transitiveScopesFor (../packages/core/src/render3/jit/module.ts:458:30)
  at setScopeOnDeclaredComponents (../packages/core/src/render3/jit/module.ts:388:28)
  at Object.flushModuleScopingQueueAsMuchAsPossible [as ɵflushModuleScopingQueueAsMuchAsPossible] (../packages/core/src/render3/jit/module.ts:59:11)
  at TestBedRender3.flushModuleScopingQueueAsMuchAsPossible [as checkGlobalCompilationFinished] (../../packages/core/testing/src/r3_test_bed.ts:400:7)
  at TestBedRender3.Object.<anonymous>.TestBedRender3.resetTestingModule (../../packages/core/testing/src/r3_test_bed.ts:231:10)
  at Function.Object.<anonymous>.TestBedRender3.resetTestingModule (../../packages/core/testing/src/r3_test_bed.ts:180:26)
  at ../../packages/core/testing/src/before_each.ts:25:13
  at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:386:30)
  at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:117:43)
  at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:385:36)
  at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone.js:143:47)

This is an example of a very simple test that fails:

import { ExampleModule } from './example.module';

describe('ExampleModule', () => {
   let exampleModule: ExampleModule;

  beforeEach(() => {
    exampleModule = new ExampleModule();
  });

  it('should create an instance', () => {
    expect(exampleModule).toBeTruthy();
  });
});

Any help would be appreciated. Thanks.


Solution

  • This ended up being an issue with barrel imports. To fix I had to remove all barrel imports and deep import all files.

    example of old:

    import {
      Example1,
      Example2
    } from 'path/to/example-folder';
    

    example of new:

    import { Example1 } from 'path/to/example1-file';
    import { Example2 } from 'path/to/example2-file';