lundi 24 avril 2017

How to prevent security errors in angular tests

I want to write tests for a component that sets the src attribute of an iframe. I have a pipe which runs DomSanitizer.bypassSecurityTrustResourceUrl on the src value normally, but I am mocking the pipe in my component test (it just returns whatever it was given with no changes) and it fails on me with a security error:

Error: inline template:2:8 caused by: unsafe value used in a resource URL context 
(see http://ift.tt/2a1DIsi)

Is there a way to prevent these errors when running tests?

I am using the angular cli to execute my tests, and use jasmine & karma.

component.html

<iframe [width]="width"
    [height]="height"
    [src]="src | safe:'url'"
    frameborder="0"
    allowfullscreen
    class="youtube-player">
</iframe>

component.spec.ts

@Component({
  template: '<cns-component [url]="url" [width]="width" [height]="height"></cns-component>'
})
class TestHostComponent {
  url: string;
  width: number;
  height: number;
}

// Angular test
describe('Component', () => {
  let comp: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;
  let el: ElementRef;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestHostComponent,
        Component,
        MockHelper.getMockPipe('safe')
      ],
      schemas: [
        NO_ERRORS_SCHEMA
      ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(TestHostComponent);
    el = fixture.debugElement.query(By.css('iframe'));
  });

  it('should generate url with necessary query params', () => {
    fixture.debugElement.componentInstance.url = 'http://www.youtube.com/somevideo';
    fixture.detectChanges();

    const videoSrc = el.nativeElement.getAttribute('src');
    expect(videoSrc).toEqual(
      `http://www.youtube.com/somevideo?${fixture.debugElement.componentInstance.queryParams}`);
  });
});

Aucun commentaire:

Enregistrer un commentaire