Alex Verzea
Alex Verzea

Reputation: 441

Jasmine doesn't recognize Angular's DomSanitizer

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!

Upvotes: 2

Views: 3418

Answers (1)

Roee Rokah
Roee Rokah

Reputation: 367

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();
  }));

Upvotes: 1

Related Questions