9新单元测试错误

9新单元测试错误

本文介绍了Angular 9新单元测试错误:“在资源URL上下文中使用不安全值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从将Angular应用程序从版本8升级到版本9之后,我在运行Jest单元测试时出现了一个新错误:

Since upgrading my Angular application from version 8 to version 9 I've got a new error appearing when I run my Jest unit test:

unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

我正在测试的组件使用DomSanitizer:

The component I am testing uses the 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:

and this url is used on an iframe:

<iframe [src]="url" />

我在Angular 9中使用Jest,并且在拍摄快照时会发生这种情况.

I am using Jest with Angular 9 and this occurs when taking a snapshot.

我的测试(我尝试过模拟而不是模拟):

My Test (I've tried mocking it and not mocking it):

  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();
  });

有人知道我该如何解决吗?

Does anyone have any ideas how I can fix this?

推荐答案

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

There is no component lifecycle in tests. You have to invoke component cycle method yourself.

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

但是由于您有一个@Input可能会变异,所以我会将逻辑从ngOnInit移到ngOnChanges,以便您的组件可以反映动态绑定更改-现在只有一张照片.

but since you have have an @Input which potentially can mutate, I would move logic from ngOnInit to ngOnChanges so your component can reflect dynamic binding changes - now it is only a one shot.

这篇关于Angular 9新单元测试错误:“在资源URL上下文中使用不安全值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:49