andreys75
@andreys75

Как тестировать pipe с зависимостью от абстрактного класса DomSanitizer?

Добрый день!

Я новичек в написании unit тестов, пытаюсь написать осмысленный тест для pipe который позволяет выводить html в шаблоне
pipe:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

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

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
			case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
			case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
			case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
			case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
			case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
			default: throw new Error(`Invalid safe type specified: ${type}`);
		}
  }
}


spec:
import { SafePipe } from './safe.pipe';
import { TestBed } from '@angular/core/testing';
import { DomSanitizer,  SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';

describe('SafePipe', () => {
  let  sanitizer: DomSanitizer;
  let  pipe: SafePipe;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DomSanitizer]
    }).compileComponents();
    sanitizer = TestBed.get(DomSanitizer);
    pipe = new SafePipe(sanitizer);

  });

  it('create an instance', () => {
     expect(pipe).toBeTruthy();
  });

  it('it should return safe HTML', () => {
    const html = '<h1>Title</h1>';
    const safeHtml = pipe.transform(html, 'html');
    expect(pipe.transform(html, 'html')).toBe(html);
  });
});

Получаю ошибку:
TypeError: this.sanitizer.bypassSecurityTrustHtml is not a function
TypeError: this.sanitizer.bypassSecurityTrustHtml is not a function
at SafePipe../src/app/core/pipes/safe.pipe.ts.SafePipe.transform (localhost:9876/_karma_webpack_/webpack:/src/app/co...

DomSanitazer абстрактный класс.

Сначала написал более простой варинат теста, с той-же ошибкой:
import { SafePipe } from './safe.pipe';
import { TestBed } from '@angular/core/testing';
import { DomSanitizer,  SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';

describe('SafePipe', () => {
  let  sanitizer: DomSanitizer;
  const pipe = new SafePipe(sanitizer);

  it('create an instance', () => {
     expect(pipe).toBeTruthy();
  });

  it('it should return safe HTML', () => {
    const html = '<h1>Title</h1>';
    expect(pipe.transform(html,'html')).toBe(html);
  });
});


Вопрос как тестировать такие pipe's
  • Вопрос задан
  • 232 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы