自从将我的Angular应用程序从版本8升级到版本9以来,当我运行Jest单元测试时,我遇到了一个新的错误:
unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
字符串
我正在测试的组件使用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 );
}
}
型
这个URL用于iframe:
<iframe [src]="url" />
型
我在Angular 9中使用Jest,这在拍摄快照时发生。
我的测试(我试着嘲笑它,而不是嘲笑它):
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();
});
型
有谁知道我该怎么解决这个问题吗?
2条答案
按热度按时间vuv7lop31#
测试中没有组件生命周期,你必须自己调用组件周期方法。
字符串
但是因为你有一个
@Input
,它可能会发生变化,我会把逻辑从ngOnInit
移到ngOnChanges
,这样你的组件就可以反映动态绑定的变化--现在它只是一个机会。v1l68za42#
字符串
这是前。