2

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

有谁知道我该如何解决这个问题?

4

1 回答 1

1

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

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

但既然你有一个@Input可能会发生变异的东西,我会将逻辑从 移动ngOnInit到 ,ngOnChanges这样你的组件就可以反映动态绑定的变化——现在它只是一个镜头。

于 2020-06-04T09:41:24.053 回答