Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test pipe with dependencies on services

I have a pipe that sanatises HTML as below:

import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser';  @Pipe({     name: 'sanitiseHtml' })  export class SanitiseHtmlPipe implements PipeTransform {  constructor(private _sanitizer: DomSanitizer) {}      transform(value: any): any {       return this._sanitizer.bypassSecurityTrustHtml(value);     }  } 

I want to test it as below:

describe('Pipe: Sanatiser', () => {     let pipe: SanitiseHtmlPipe;      beforeEach(() => {         pipe = new SanitiseHtmlPipe(new DomSanitizer());     });      it('create an instance', () => {         expect(pipe).toBeTruthy();     });  }); 

The DomSanatizer is an abstract class which is autowired by typescript by passing it into a constructor:

constructor(private _sanitizer: DomSanitizer) {} 

Currently I get the typescript errror:

Cannot create an instance of the abstract class 'DomSanitizer'.

Does anyone know what typescript does when instantiating dependencies passed into a constructor in Angular? Or what the way to test something like this is?

like image 847
Ben Taliadoros Avatar asked Nov 27 '17 15:11

Ben Taliadoros


People also ask

How do you test a service with dependencies?

Angular services can be tested in a couple of different ways, two most prominent being isolated tests and using the Angular TestBed . However, things get interesting when the service under test has dependencies (injected using Angular's dependency injection).

How do I unit test a service with angular components?

Mock Service Dependency In Angular For unit testing the method, you need to mock the service method getPosts to test the component method. Let's start by writing unit test for testing method getPostDetails when the response from service method getPosts is an empty array. Add the following unit test case to the app.


1 Answers

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();   }));  }); 
like image 74
Jota.Toledo Avatar answered Sep 18 '22 17:09

Jota.Toledo