代码之家  ›  专栏  ›  技术社区  ›  Michahell

Angular 6单元测试组件,具有域消毒剂依赖性

  •  3
  • Michahell  · 技术社区  · 6 年前

    DomSanitizer 依赖项,如何模拟/存根这个依赖项?

    因为 是一个 Abstract bypassSecurityTrustHtml 真的很像。

    消毒剂 ,如何将实际实现注入抽象类?

    组件中的实际语句如下所示:

    this.trustedString = <string>this.domSanitizer.bypassSecurityTrustHtml(trustedHTML);
    

    TestBed 安装程序如下:

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [
          BrowserModule,
          // other modules
        ],
        providers: [
          {
            provide: DomSanitizer,
            useValue: {
              bypassSecurityTrustHtml: () => 'safeString'
            }
          },
          // more providers
        ],
        declarations: [ TheComponent ],
        schemas: [ NO_ERRORS_SCHEMA ]
      })
        .compileComponents();
    }));
    

    我在Chrome中得到的业力(不是无头)的具体错误是:

    TypeError: view.root.sanitizer.sanitize is not a function

    错误属性:对象({ngDebugContext:DebugContext{view:Object({def:Object({factory:Function,nodeFlags:16793601,rootNodeFlags:1,nodematchedquerys:0,标志:0,节点:[Object({nodeIndex:0,parent:null,renderParent:null,bindingIndex:0,outputIndex:0,checkIndex:0,标志:1,childFlags:16793601,directChildFlags:16777217,childMatchedQueries:0,matchedQueries:Object({}),matchedQueryID:0,引用:Object({}),ngContentIndex:null,childCount:5,绑定:[],bindingFlags:0,输出:[],元素:对象({ns:null,名称:null,属性:[],模板:null,组件提供程序:null,组件视图:null,componentrendertype:null,publicProviders:null({}),allProviders:null({}),handleEvent:Function},provider:null,text:null,query:null,ngContent:null},Object({nodeIndex:1,parent:Object({nodeIndex:0,parent:null,renderParent:null,bindingIndex:0,outputIndex:0,checkIndex:0,flags:1,childFlags:16793601,directChildFlags:16777217。。。 在 在checkAndUpdateElementValue(webpack://./node\u modules/@angular/core/fesm5/core.js?:8189:13) 在checkAndUpdateElementInline(webpack://./node\u modules/@angular/core/fesm5/core.js?:8136:24) 在checkAndUpdateNode上(webpack://./node\u modules/@angular/core/fesm5/core.js?:10443:16) 在debugCheckAndUpdateNode(webpack://./node\u modules/@angular/core/fesm5/core.js?:11076:38) at Object.eval[作为updaterder](ng:///DynamicTestModule/ConversationMessageComponent.ngfactory.js:84:5) 在Object.debugUpdateRenderer[as updateRenderer](webpack:///node_modules/@angular/core/fesm5/core.js?:11054:21) 在checkAndUpdateView(webpack://./node\u modules/@angular/core/fesm5/core.js?:10430:14)

    1 回复  |  直到 5 年前
        1
  •  17
  •   Pavel B.    6 年前

    作为解决方法,请尝试添加 sanitize: () => 'safeString',

    ...
    useValue: {
      sanitize: () => 'safeString',
      bypassSecurityTrustHtml: () => 'safeString'
    }
    ...
    
        2
  •  1
  •   Krzysztof Grzybek    5 年前

    如果要保留该值,请使用:

    {
      provide: DomSanitizer,
      useValue: {
        sanitize: (ctx, val) => val,
        bypassSecurityTrustResourceUrl: val => val,
      },
    }