Jasmine不承认Angular的DomSanitizer

时间:2018-05-31 19:08:14

标签: angular jasmine testbed angular-dom-sanitizer

我正在使用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('...');
  });

此外,DomSanitizerTestBed 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

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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