簡體   English   中英

我如何去測試依賴於 DomSanitizer 的管道?

[英]How do I go about testing a Pipe which depends on DomSanitizer?

角度版本:8.1.2
測試工具:由ng new預先安裝的 Karma 和 Jasmine

我目前正在從事我的第一個 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);
  }

}

自動生成的規范文件看起來像這樣:

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

在我運行測試之前,VSCode 告訴我這SafeResourceUrlPipe ,因為SafeResourceUrlPipe的構造函數需要一個參數。 到目前為止一切順利,但我現在不知道該怎么辦。 我不能只使用new DomSanitizer ,因為它是一個抽象類。

我嘗試過的是創建一個實現 DomSanitizer 的模擬類,但是我只能測試管道是否已創建,而且我之前已經知道了。 我想測試的是它是否正確地完成了轉換輸入的工作,但是當我偽實現主要依賴項時,我幾乎無法測試它。

我已經對此進行了一些谷歌搜索,我懷疑它會變得很明顯,但我找不到它。

我建議使用 Angular Testbed 像這樣注入 dom sanitizer 的模擬。

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

然后

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

ps useValue在這里很重要。 如果你只在這里提供一個值,那么它很好。 如果你想用一個完整的useClass類來替換它,你必須使用useClass (大多數人陷入困境的小錯誤)

export class MockDomSanitizer {
    bypassSecurityTrustResourceUrl() {}
    otherMethods(){}
}

這應該允許您使用模擬的 dom sanitizer 方法運行管道。

您不需要模擬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();
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM