Angular 9新单元测试错误:“资源URL上下文中使用了不安全的值”

问题描述 投票:0回答:1

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

}

并且此网址用于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();
  });

有人对我该如何解决有任何想法吗?

angular jest angular-dom-sanitizer
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.