How to mock Pipe when testing Component

harunurhan picture harunurhan · Sep 2, 2016 · Viewed 40.8k times · Source

Currently I am overriding providers to use mocked services like this:

beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb.overrideProviders(AddFieldToObjectDropdownComponent,
        [
             provide(ServiceA, { useClass: MockServiceA })),
             provide(ServiceB, { useClass: MockServiceB }))
        ])
    ...

I want to do same thing for pipes that the component uses. I tried, provide(PipeA, { useClass: MockPipeA }) and provide(PipeA, { useValue: new MockPipeA() }) but both didn't work.

Answer

Dinistro picture Dinistro · Jan 24, 2017

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;
    }
}