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

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

我尝试测试 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 文件中的依赖项:

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

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

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

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

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