Test pipe with dependencies on services

前端 未结 3 1671
陌清茗
陌清茗 2021-02-02 08:41

I have a pipe that sanatises HTML as below:

import { Pipe, PipeTransform } from \'@angular/core\';
import { DomSanitizer } from \'@angular/platform-browser\';

@         


        
相关标签:
3条回答
  • 2021-02-02 09:22

    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();
      })); 
    });
    
    0 讨论(0)
  • 2021-02-02 09:23

    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();
      });
    
    0 讨论(0)
  • 2021-02-02 09:27

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题