Jest.js Angular 9新单元测试错误:“unsafe value used in a resource URL context”

vcudknz3  于 6个月前  发布在  Jest
关注(0)|答案(2)|浏览(68)

自从将我的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();
  });


有谁知道我该怎么解决这个问题吗?

vuv7lop3

vuv7lop31#

测试中没有组件生命周期,你必须自己调用组件周期方法。

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

字符串
但是因为你有一个@Input,它可能会发生变化,我会把逻辑从ngOnInit移到ngOnChanges,这样你的组件就可以反映动态绑定的变化--现在它只是一个机会。

v1l68za4

v1l68za42#

beforeEach(async(() => {
    sanitizerSpy = jasmine.createSpyObj('DomSanitizer', ['bypassSecurityTrustResourceUrl']);

    TestBed.configureTestingModule({
      declarations: [ ExampleComponent ],
      providers: [
        DomSanitizer
      ]
    })
    .compileComponents();
  }));
  beforeEach(() => {
    sanitizerSpy.bypassSecurityTrustResourceUrl.and.callFake((value) => value as SafeResourceUrl);
    fixture = TestBed.createComponent(ExampleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

字符串
这是前。

相关问题