首页 > 解决方案 > 错误:模块“DynamicTestModule”导入了意外的值“DomSanitizer”。请添加@NgModule 注释

问题描述

我尝试测试 DomSanitizer 导入。

但我仍然收到此错误:

Error: Unexpected value 'DomSanitizer' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

我的测试用例如下所示:

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, DomSanitizer, DossierFileService, ErrorProcessor, MatDialog, BrowserModule],
      declarations: [ DossierPersonalDataComponent ],
      providers: [{

        provide: DomSanitizer,
        useValue: {
          sanitize: () =>'safeString',
          bypassSecurityTrustHtml: () => 'safeString'
        }

      }]
    })
    .compileComponents();
  }));

那么我必须改变什么?

谢谢

这是 ts 文件中的 de 依赖项:

constructor(
    private dossierService: DossierService,
    private route: ActivatedRoute,
    private sanitizer: DomSanitizer,
    private dossierFileService: DossierFileService,
    private errorProcessor: ErrorProcessor,
    private dialog: MatDialog
  )

标签: javascriptangularjasmineistanbul

解决方案


DomSanitizer从中删除imports。您应该只导入模块,而不是服务。你应该提供服务。如果DossierFileService,ErrorProcessor是服务(我不确定 MatDialog 是否),请将它们移至提供者。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, MatDialog, BrowserModule],
      declarations: [ DossierPersonalDataComponent ],
      providers: [{

        provide: DomSanitizer,
        useValue: {
          sanitize: () =>'safeString',
          bypassSecurityTrustHtml: () => 'safeString'
        }

      },
      DossierFileService,
      ErrorProcessor,
     ]
    })
    .compileComponents();
  }));

推荐阅读