angular - Auth0 Angular error during unit test : U

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

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

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

示例规范:

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

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

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

此外,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/

相关文章:

ruby-on-rails - 无法使用 octokit 连接到 Github 帐户

java - ThreadPoolExecutor.shutdownNow() 没有在 Thread

c# - 在 Visual Studio 中替换后删除空行

ios - FaSTLane Match 环境变量未被 build_app 获取

pytorch - Pytorch 中软标签的交叉熵

fortran - gfortran 与 MKL 的链接导致 'Intel MKL ERROR: P

c++ - 无法构建 Boost Spirit 示例 conjure2

reactjs - 如何在 React 中使用 map 输出嵌套对象的内容?

javascript - Typescript reducer 的 switch case type

android - 我们如何保存和恢复 Android StateFlow 的状态?