如何测试依赖于 DomSanitizer 的 Pipe?

Rum*_*fel 6 abstract-class angular angular-test angular-dom-sanitizer

Angular 版本:8.1.2
测试工具:Karma 和 Jasmine,由ng new

我目前正在开发我的第一个 Angular 项目。作为其中的一部分,我创建了一个调用DomSanitizer.bypassSecurityTrustResourceUrl. 我这样做是为了能够在 iframe 中使用它们。我现在想对这个管道进行测试。这是它的代码:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from "@angular/platform-browser";

@Pipe({
  name: 'safe'
})
export class SafeResourceUrlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(url: string): SafeResourceUrl | string {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}
Run Code Online (Sandbox Code Playgroud)

自动生成的规范文件看起来就像这样:

import { TestBed, async } from '@angular/core/testing';
import { SafeResourceUrlPipe } from './safe-resource-url.pipe';
import { DomSanitizer } from '@angular/platform-browser';

describe('Pipe: SafeResourceUrle', () => {
  it('should create an instance', () => {
    let pipe = new SafeResourceUrlPipe();
    expect(pipe).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

在我运行测试之前,VSCode 就告诉我这不起作用,因为SafeResourceUrlPipe的构造函数需要一个参数。到目前为止一切都很好,但我现在不知道该怎么办。我不能只使用new DomSanitizer,因为它是一个抽象类。

我尝试过创建一个实现 DomSanitizer 的模拟类,但是除了测试管道是否已创建之外,我不能做更多的事情,而且我之前已经知道了。我想测试的是它是否正确地完成了转换输入的工作,但是当我伪实现主要依赖项时我几乎无法测试这一点。

我已经对此进行了一些谷歌搜索,我怀疑它会变得很明显,但我找不到它。

j3f*_*3ff 14

您不需要模拟DomSanitizer,它在您导入时变得可用BrowserModule。因此,您只需要在配置测试模块时导入模块并使用TestBed.get()方法检索它以将其传递给管道构造函数。

import { BrowserModule, DomSanitizer } from '@angular/platform-browser';

describe('Pipe: SafeResourceUrl', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [BrowserModule],
    });
  });

  it('should create an instance', () => {
    const domSanitizer = TestBed.get(DomSanitizer);
    const pipe = new SafeResourceUrlPipe(domSanitizer);
    expect(pipe).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 1

我建议使用 Angular Testbed 来注入 dom sanitizer 的模拟,如下所示。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SafeResourceUrlPipe],
      providers: [
           SafeResourceUrlPipe,
          { provide: DomSanitizer, useValue: {bypassSecurityTrustResourceUrl(){}}
     ]
    });
  }));
Run Code Online (Sandbox Code Playgroud)

然后

describe('Pipe: SafeResourceUrle', () => {
  it('should create an instance', () => {
    let pipe = TestBed.get(SafeResourceUrlPipe);
    expect(pipe).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

psuseValue这里很重要。如果您只在这里提供一个值,那就没问题了。如果你想用一个完整的模拟类替换它,你必须useClass(大多数人都会遇到的小失误)

export class MockDomSanitizer {
    bypassSecurityTrustResourceUrl() {}
    otherMethods(){}
}
Run Code Online (Sandbox Code Playgroud)

这应该允许您使用模拟的 dom sanitizer 方法运行管道。