首页 > 解决方案 > Jasmine 无法识别 Angular 的 DomSanitizer

问题描述

我正在使用 Jasmine 对 Angular 5 应用程序进行单元测试。我到了需要测试一个依赖于的函数的地步DomSanitizer

loadImage() {
  this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${this.assetUrl})`);
}

我验证了这个函数可以完美运行,这意味着它DomSanitizer已经在构造函数中并且它的语法是正确的。

我的单元测试如下:

it('loads the Image', () => {
    component.loadImage()
    fixture.detectChanges();
    expect(component.imageUrl).toBe('...');
  });

此外,DomSanitizer是的一部分TestBed providers

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        CommonModule
      ],
      declarations: [
        MyComponent
      ],
      providers: [
        DomSanitizer
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

然而,Jasmine 在对函数进行单元测试时抛出了这个错误:

ERROR: 'Unhandled Promise rejection:', '_this.sanitizer.bypassSecurityTrustStyle is not a function', '; Zone:', 'angular', '; Task:', 'Promise.then', '; Value:', TypeError: _this.sanitizer.bypassSecurityTrustStyle is not a function

有任何想法吗?

谢谢!

标签: angularjasminetestbedangular-dom-sanitizer

解决方案


将其更改为 BrowserModule 而不是 CommonModule 并且还可以省略 DomSanitizer:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        BrowserModule
      ],
      declarations: [
        MyComponent
      ]
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

推荐阅读