Answer the question
In order to leave comments, you need to log in
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}`);
}
}
}
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);
});
});
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);
});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question