本文介绍了具有DomSanitizer依赖关系的Angular 6单元测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在仅创建(实例化)具有DomSanitizer依赖项的组件的单元测试中,如何模拟/存根此依赖项?

In a unit test to just create (instantiate) a component that has a DomSanitizer dependency, how does one mock / stub this dependency?

因为DomSanitizerAbstract类,所以我不知道bypassSecurityTrustHtml的方法签名是什么样子.

Because DomSanitizer is an Abstract class, I have no idea what the method signature of bypassSecurityTrustHtml really looks like.

如果不打算模拟/存根DomSanitizer,应该如何继续向抽象类中注入实际的实现?

And if it's not intended to mock / stub DomSanitizer, how should one proceed to inject the actual implementation iso the abstract class?

该组件中的实际声明如下:

actual statement in the component looks like:

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的Karma中遇到的具体错误(不是无头)是

The specific error that I'm getting in Karma in Chrome (not headless) is this:

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

推荐答案

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

As a workaround, try add sanitize: () => 'safeString',

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

这篇关于具有DomSanitizer依赖关系的Angular 6单元测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 12:22