Angular2 - The expected safevalue should use [property] = binding

I am writing a test for SafePipe. The method uses bypassSecurityTrustResourceUrl()

. I searched for available solutions and tried them, but unfortunately it didn't work for me. Mistake

The expected SafeValue is to use [property] = binding: Cross (see http://g.co/ng/security#xss ) as a "cross-site request".

What am I doing here?

import {Pipe, PipeTransform} from "@angular/core";
import {DomSanitizer} from "@angular/platform-browser";

@Pipe({name: 'safe'})
 export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
 }

 public transform(url: string): any {
   return this.sanitizer.bypassSecurityTrustResourceUrl(url);
 }
}

      

Test:

import {SafePipe} from './safe.pipe';
import {DomSanitizer} from "@angular/platform-browser";
import {DomSanitizerImpl} from "@angular/platform-browse/src/security/dom_sanitization_service";

fdescribe('SafePipe', () => {
  let pipe: SafePipe;
  let sanitizer: DomSanitizer = new DomSanitizerImpl();
  beforeEach(() => {
    pipe = new SafePipe(sanitizer);
  });

  it('should transform', () => {
    expect(pipe.transform("Cross <script>alert('Hello')</script>")).toBe("Cross alert('Hello')");
  });
});

      

+3


source to share


1 answer


sanitizer.bypassSecurityTrustResourceUrl

returns a class SafeResourceUrlImpl

and you cannot convert it to string (jasmine is trying to convert it internally).

abstract class SafeValueImpl implements SafeValue {
  constructor(public changingThisBreaksApplicationSecurity: string) {
    // empty
  }

  abstract getTypeName(): string;

  toString() {
    return `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
        ` (see http://g.co/ng/security#xss)`;
  }
}

      

You should use a method instead DomSanitizer.sanitize

(Angular uses it when applying a type property [url]="value | safe"

)



it('should transform', () => {
  const safeResourceUrl = pipe.transform("Cross <script>alert('Hello')</script>");
  const sanitizedValue = sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeResourceUrl);

  expect(sanitizedValue).toBe("Cross <script>alert('Hello')</script>");
});

      

PS. Here I am assuming that you have a typo in the expression toBe

and that you expect the string to preserve the tags script

.

A complete example can be found in Plunker

+6


source







All Articles