2

I am unit testing an Angular 5 app with Jasmine. I got to the point where I need to test a function that relies on the DomSanitizer:

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

I verified that this function works perfectly, meaning that DomSanitizer is already in the constructor and it's syntax is correct.

My unit test is as follows:

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

Moreover, DomSanitizer is part of the TestBed providers:

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

Yet, Jasmine throws this error when unit-testing the function:

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

Any ideas?

Thanks!

Alex Verzea
  • 421
  • 1
  • 11
  • 30

1 Answers1

1

change it to be BrowserModule instead of CommonModule and also, DomSanitizer can be ommited:

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