【问题标题】:Angular 9 new unit test error: "unsafe value used in a resource URL context"Angular 9 新的单元测试错误:“资源 URL 上下文中使用的不安全值”
【发布时间】:2020-09-23 05:53:05
【问题描述】:

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

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

【问题讨论】:

    标签: angular jestjs angular-dom-sanitizer


    【解决方案1】:

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

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

    但由于您有一个可能会发生变异的 @Input,因此我会将逻辑从 ngOnInit 移动到 ngOnChanges,以便您的组件可以反映动态绑定更改 - 现在它只是一次尝试。

    【讨论】:

    • 虽然您对生命周期的评论是正确的,但我仍然无法摆脱错误。
    • 我还需要删除我对 DomSanitizer 的模拟。
    • 这很明显,因为您实际上需要绕过安全性——因为这就是错误的全部意义所在。
    • 最后的工作是什么 - 使用 Mock 管道、oninit 和提供程序?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多