angular - Auth0 Angular error during unit test : Unexpected value 'AuthModule' imported by the module 'DynamicTestModule' . 请添加@NgModule注解

标签 angular jestjs auth0

我们正在我们的 Angular 12 应用程序中迁移到使用 Jest 而不是 Karma,并且在我们使用 Auth0 的规范文件中全面出错:

模块“DynamicTestModule”导入的意外值“AuthModule”。请添加@NgModule 注解。

奇怪的部分:我们目前使用 Karma 进行的单元测试非常顺利,没有错误

示例规范:

beforeEach(waitForAsync(() => {
  TestBed.configureTestingModule({
    imports: [
      AuthModule.forRoot(mockAuth0Config),
      HttpClientTestingModule
    ],
    declarations: [
      MyComponent
    ]
  }).compileComponents();
}));

Auth0 的库在我看来不错(它不是组件或服务,它确实是使用 ModuleWithProviders 接口(interface)的“模块”:

enter image description here

我遇到的所有其他问题都是组件或服务导入不正确,而这里不是这种情况。

此外,AuthModule.forRoot({...}) 用于imports 我们的 app.module.ts 就好了是将 Auth0 与 Angular 一起使用的基础,它们在生产中都可以正常工作。

上述错误只会在 Jest 中运行我们现有的测试时发生。

最佳答案

我得出的解决方案是完全绕过 Auth0 并创建一个模仿相同功能和参数的模拟 Auth0 模块。

@NgModule({
  imports: [],
  exports: []
})
export class AuthModuleMock {
  /**
   * Mock forRoot method
   * @param config The optional configuration for the SDK.
   */
  static forRoot(config ?: AuthConfig) : ModuleWithProviders<AuthModule> {
    return {
      ngModule: AuthModule,
      providers: [
        AuthService,
        AuthGuard,
        {
          provide: AuthConfigService,
          useValue: config
        },
        {
          provide   : Auth0ClientService,
          useFactory: () : any => { return; },
          deps      : [
            AuthClientConfig
          ]
        }
      ]
    };
  }
}

这是将它们导入到 .spec 文件中,而不是 Auth0 提供的 AuthModule

beforeEach(waitForAsync(() => {
  TestBed.configureTestingModule({
    imports: [
      AuthModuleMock.forRoot(mockAuth0Config),
      HttpClientTestingModule
    ],
    declarations: [
      MyComponent
    ]
  }).compileComponents();
}));

关于angular - Auth0 Angular error during unit test : Unexpected value 'AuthModule' imported by the module 'DynamicTestModule' . 请添加@NgModule注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70429415/

相关文章:

meteor - 如何在 Meteor JS 中使用 Auth0 登录

javascript - 操作指南 : Angular library divided in independent feature sub libraries

unit-testing - Jest 错误: Test suite failed to run,如何解决?

javascript - enzyme :如何测试浅层组件的交互

reactjs - 用 Jest 测试时如何选择dom

reactjs - 集成 Auth0 和 Hasura 时找不到访问被拒绝的服务

angular - 如何在 Angular 自定义组件中一起添加 ngModel 和 formControlName?

Javascript Angular 使用不同 .ts 文件中的代码

Angular 7 - 自定义库 - 无法导出简单类

testing - 如何在使用 Cypress 的 E2E 测试中登录 Auth0?