How to mock Pipe when testing Component
You can add your mockpipes in the declarations
of the TestBed
:
TestBed.configureTestingModule({ declarations: [ AppComponent, MockPipe ], ...
The MockPipe
needs to have the @Pipe
decorator with the original name.
import {Pipe, PipeTransform} from '@angular/core';@Pipe({name: 'pipename'})class MockPipe implements PipeTransform { transform(value: number): number { //Do stuff here, if you want return value; }}
To stub the pipe, use Dinistro's answer. To spy on the pipe, you can complement that with the following:
let pipeSpy: jasmine.Spy;beforeEach(() => { TestBed.configureTestingModule... pipeSpy = spyOn(MockPipe.prototype, 'transform');};it('should do whatever', () => { doYourStuff(); expect(pipeSpy).toHaveBeenCalled();}
If you want reusable util function for mocking pipes, you can try this option:
export function mockPipe(options: Pipe): Pipe { const metadata: Pipe = { name: options.name }; return <any>Pipe(metadata)(class MockPipe {});}
And then just call this function inside the TestBed declarations array:
TestBed.configureTestingModule({ declarations: [ SomeComponent, mockPipe({ name: 'myPipe' }), mockPipe({ name: 'myOtherPipe' }) ], // ...}).compileComponents();