Test pipe with dependencies on services

前端 未结 3 1707
陌清茗
陌清茗 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: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;
      }
    }
    

提交回复
热议问题