【问题标题】:TypeError: Cannot read properties of undefined (reading 'ngModule')类型错误:无法读取未定义的属性(读取 \'ngModule\')
【发布时间】:2023-01-21 19:55:24
【问题描述】:

运行测试我得到这个错误类型错误:无法读取未定义的属性(读取“ngModule”)

我不完全知道是什么导致了这个错误,但谷歌说循环依赖问题,但我不知道从哪里开始。 使用带有角度和笑话的 NX-monorepo 进行测试 甚至我与组件相关的测试也因同样的错误而失败, 谢谢!

模块.spec.ts

import { StatusOverviewModule } from './status-overview.module';

describe('StatusOverviewModule', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StatusOverviewModule],
    });
  });

  it('initializes', () => {
    const module = TestBed.inject(StatusOverviewModule);
    expect(module).toBeTruthy();
  });
});

状态-overview.module

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { TRANSLOCO_SCOPE } from '@ngneat/transloco';
import { SohoComponentsModule } from 'ids-enterprise-ng';

import {
  HttpAuthInterceptor,
  IonDeskIntegrationModule,
  ModuleAccessibilityGuard,
  PermissionResource,
} from '@core/ion-desk-integration';
import { scopeLoader, TranslationsModule, TranslationsResolver } from '@core/translations';
import { TilesModule } from '@shared/tiles';

import { StatusOverviewHomeComponent } from './components/status-overview-home/status-overview-home.component';
import { StatusTileCircleComponent } from './components/status-tile-circle/status-tile-circle.component';
import { LOCAL_REST_URL, REST_ENDPOINT } from './constants/status-overview.constants';
import { HttpErrorInterceptor } from './interceptors/http-error.interceptor';
import { LongNumberConversion } from './pipe/long-conversion.pipe';
import { StatusDataService } from './services/status-data.service';
import { StatusOverviewComponent } from './status-overview.component';

export const statusOverviewRoutes: Routes = [
  {
    path: '',
    component: StatusOverviewComponent,
    canActivate: [ModuleAccessibilityGuard],
    data: {
      permissionResource: PermissionResource.ANY,
    },
    resolve: {
      translations: TranslationsResolver,
    },
  },
];

@NgModule({
  imports: [
    CommonModule,
    SohoComponentsModule,
    TranslationsModule,
    TilesModule,
    RouterModule.forChild(statusOverviewRoutes),
    FormsModule,
    HttpClientModule,
    IonDeskIntegrationModule.forFeature({
      devApiPath: LOCAL_REST_URL + '/' + REST_ENDPOINT,
      serverApiPath: REST_ENDPOINT,
    }),
  ],
  providers: [
    {
      provide: TRANSLOCO_SCOPE,
      useValue: {
        scope: 'statusOverview',
        loader: scopeLoader((lang, root) => import(`../assets/${root}/${lang}.json`)),
      },
    },
    { provide: HTTP_INTERCEPTORS, 
      useClass: HttpErrorInterceptor,
       multi: true },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpAuthInterceptor,
      multi: true,
    },
    StatusDataService,
  ],
  declarations: [StatusOverviewComponent, StatusOverviewHomeComponent, StatusTileCircleComponent, LongNumberConversion],
})
export class StatusOverviewModule {}

【问题讨论】:

  • 你到底为什么要注入模块?我什至不知道这样做是否正确

标签: angular jestjs ts-jest nrwl-nx jest-preset-angular


【解决方案1】:

我猜你错过了等待模块创建的时间。 试试这样:

   await TestBed.configureTestingModule

【讨论】:

  • 尝试添加等待,仍然出现相同的错误!
  • 拜托,您能否提供一个示例来清楚地说明您所面临的问题?理想情况下,您可以将代码放入 stackblitz.com 之类的在线 IDE 中,然后立即有人可以开始解决问题,而无需首先重新创建它。
  • 为了响应此错误,我多次看到此评论。我怀疑最低限度地重现这一点需要了解原因。就我而言,上下文太大,我无法以孤立的方式重现它。希望解决这个错误的人能说出来。
【解决方案2】:

由于这是谷歌搜索结果中出现的第一篇文章,因此对于此错误,将在此处进行解答。

在谷歌搜索答案后,最终只是调试我发现这个错误意味着你正在导入某处的模块之一确实包含未定义的而不是模块。 这可能是由于 barrel-imports 造成的,但最简单的方法是从导入中删除损坏的模块。

要找出在哪个模块中导入了未定义的模块,您可能必须修改 @angular/core 包中的源文件之一。它的名称是core.mjs 或类似的名称。找到compileNgModuleDefs 函数并修改getter 以在包含未定义导入的情况下打印模块名称:

    Object.defineProperty(moduleType, NG_MOD_DEF, {
        configurable: true,
        get: () => {
            if (ngModuleDef === null) {
                if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
                    // We need to assert this immediately, because allowing it to continue will cause it to
                    // go into an infinite loop before we've reached the point where we throw all the errors.
                    throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
                }
                const compiler = getCompilerFacade({ usage: 0 /* Decorator */, kind: 'NgModule', type: moduleType });
                // these three lines where added
                if(ngModule.imports && ngModule.imports.some(i => i === undefined)) {
                    console.log(moduleType.name)
                }
                ngModuleDef = compiler.compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
                    type: moduleType,
                    bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY).map(resolveForwardRef),
                    declarations: declarations.map(resolveForwardRef),
                    imports: flatten(ngModule.imports || EMPTY_ARRAY)
                        .map(resolveForwardRef)
                        .map(expandModuleWithProviders),
                    exports: flatten(ngModule.exports || EMPTY_ARRAY)
                        .map(resolveForwardRef)
                        .map(expandModuleWithProviders),
                    schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
                    id: ngModule.id || null,
                });
                // Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
                // should verify that there are no unknown elements in a template. In AOT mode, that check
                // happens at compile time and `schemas` information is not present on Component and Module
                // defs after compilation (so the check doesn't happen the second time at runtime).
                if (!ngModuleDef.schemas) {
                    ngModuleDef.schemas = [];
                }
            }
            return ngModuleDef;
        }
    });

根据您使用的角度版本,此功能可能会有所不同。对我来说是@angular/core@13.3.9

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 2018-04-29
    • 2022-12-08
    • 2022-12-01
    • 2022-12-21
    • 2022-12-24
    • 2022-12-25
    • 2023-02-06
    相关资源
    最近更新 更多