A
A
andreys752019-10-17 13:57:25
Angular
andreys75, 2019-10-17 13:57:25

How to test a pipe with a dependency on the DomSanitizer abstract class?

Good afternoon!
I'm new to writing unit tests, I'm trying to write a meaningful pipe test that allows html to be output in a
pipe template:

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

I get the error: TypeError :
this.sanitizer.bypassSecurityTrustHtml is not a
function 9876/_karma_webpack_/webpack:/src/app/co... DomSanitazer abstract class First I wrote a simpler version of the test, with the same error:
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);
  });
});

The question is how to test such pipe's

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question