我正在为SafePipe编写测试。该方法使用bypassSecurityTrustResourceUrl()
。我搜索了可用的解决方案并尝试了它们但不幸的是,它对我没有帮助。错误是
预期的SafeValue必须使用[property] = binding:Cross(请参阅http://g.co/ng/security#xss)为“Cross site Request”。
我在这做什么错了?
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);
}
}
测试是:
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')");
});
});
sanitizer.bypassSecurityTrustResourceUrl
方法返回SafeResourceUrlImpl
类,你不能将它转换为字符串(jasmine试图在内部转换它)。
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)`;
}
}
您应该使用DomSanitizer.sanitize
方法(Angular在应用[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。在这里,我假设你在toBe
语句中有拼写错误,并且你期望字符串将保存script
标签。
您可以在Plunker找到完整示例
接受的答案略有不同:将管道的SafeValue
输出与已消毒的预期值进行比较:
import { RichtextPipe } from './richtext.pipe';
import {BrowserModule, DomSanitizer} from "@angular/platform-browser";
import {TestBed} from "@angular/core/testing";
describe('RichtextPipe', () => {
let domSanitizer: DomSanitizer;
let pipe: RichtextPipe;
beforeEach(() => {
TestBed
.configureTestingModule({
imports: [
BrowserModule
]
});
domSanitizer = TestBed.get(DomSanitizer);
pipe = new RichtextPipe(domSanitizer);
});
it('should convert EventPage page link', () => {
// Setup
const html = '<a id="1" linktype="page" pagetype="EventPage">foo</a>';
// Test
const result = pipe.transform(html);
// Assert
const expected = domSanitizer.bypassSecurityTrustHtml('<a routerLink="/events/1">foo</a>');
expect(result).toEqual(expected);
});
});
在这个例子中,RichtextPipe
使用bypassSecurityTrustHtml
来转换输出。如果您的管道使用不同的旁路方法,那么您可能应该在预期值上使用相同的方法。