3

Since upgrading my Angular application from version 8 to version 9 I've got a new error appearing when I run my Jest unit test:

unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

The component I am testing uses the DomSanitizer:

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

export class ExampleComponent implements OnInit {

  @Input() path: string;
  url: SafeResourceUrl;

  constructor(
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit(){
    this.url = this.sanitizer.bypassSecurityTrustResourceUrl( this.path );
  }

}

and this url is used on an iframe:

<iframe [src]="url" />

I am using Jest with Angular 9 and this occurs when taking a snapshot.

My Test (I've tried mocking it and not mocking it):

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ExampleComponent ],
      providers: [
        {
          provide: DomSanitizer,
          useValue: {
            bypassSecurityTrustResourceUrl: () => ''
          }
        }
      ]
    })
    .compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(ExampleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should render', () => {
    expect(fixture).toMatchSnapshot();
  });

Does anyone have any ideas how I can fix this?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Ewan
  • 378
  • 3
  • 14

1 Answers1

0

There is no component lifecycle in tests. You have to invoke component cycle method yourself.

  beforeEach(() => {
    fixture = TestBed.createComponent(ExampleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.ngOnInit();
  });

but since you have have an @Input which potentially can mutate, I would move logic from ngOnInit to ngOnChanges so your component can reflect dynamic binding changes - now it is only a one shot.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99