I have a pipe that sanatises HTML as below:
import { Pipe, PipeTransform } from \'@angular/core\';
import { DomSanitizer } from \'@angular/platform-browser\';
@
Because of the DI in your pipe, you need to configure a test environment (test bed) to resolve the dependency:
import { BrowserModule, DomSanitizer } from '@angular/platform-browser';
import { inject, TestBed } from '@angular/core/testing';
describe('SanitiseHtmlPipe', () => {
beforeEach(() => {
TestBed
.configureTestingModule({
imports: [
BrowserModule
]
});
});
it('create an instance', inject([DomSanitizer], (domSanitizer: DomSanitizer) => {
let pipe = new SanitiseHtmlPipe(domSanitizer);
expect(pipe).toBeTruthy();
}));
});
just in case anyone would like to reuse the constructor of the Pipe, you can use the TestBed to acheive the same result :
let pipe: SafeHtmlPipe;
let sanitized: DomSanitizer
beforeEach(async() => {
TestBed.configureTestingModule({
providers: [DomSanitizer]
});
sanitized = TestBed.get(DomSanitizer);
pipe = new SafeHtmlPipe(sanitized);
});
it('create an instance', () => {
expect(pipe).toBeTruthy();
});
In case you want to mock the whole providers and don't wanna use the constructor, this is how I do it (with Jest but replace the spy with your regular jasmine.createSpyObj)
spec
describe("MyPipe", () => {
let pipe: MyPipe;
const myServiceSpy = { myFunction: jest.fn() };
beforeEach(() => {
jest.clearAllMocks();
TestBed.configureTestingModule({
providers: [
MyPipe,
{
provide: MyService,
useValue: myServiceSpy
}
]
});
pipe = TestBed.inject(myPipe);
});
it("create an instance", () => {
expect(pipe).toBeTruthy();
});
});
pipe
@Pipe({
name: "myPipe"
})
export class MyPipe implements PipeTransform {
constructor(private readonly myService: MyService) {}
transform(value: Item): boolean {
// stuff with your service
return true;
}
}