How to test pipes in angular

I have a scenerio where a pipe return the class name based on the input and my test case is getting failed if I trying to test the pipe. My implementation is as follows, can anyone pls help.Thanks.
I have a html as follows,

   <div [class]="type | functionTester: getNameOfClass: this"> 
    .... 
    </div>
     

Ts,

   type = 'high';
      getNameOfClass() {
       if (type === 'high') {
         return 'HIGH';
       } else {
         return 'LOW';
       }
    }

Pipe,

   export class functionTesterPipe implements PipeTransform {
    public transform(
       value: any,
       handler: (value: any) => any,
       context?: any
      ): any {
       if (context) {
        return handler.call(context, value);
       }

         return handler(value);
       }
     }

Spec,

 const { find } = await shallow
     render({
      bind: { chartData: chartData, type: 'ORG_BENCHMARK' }
    });
  const pipe = new functionTesterPipe();
  expect(pipe.transform('high', instance.prepareClassName)).toBe('High');
  fixture.detectChanges();
  expect(find('.High').length).toBe(1); -> Failing at this line as [expect 0 to be 1]


    

I have a scenerio where a pipe return the class name based on the input and my test case is getting failed if I trying to test the pipe. My implementation is as follows, can anyone pls help.Thanks.

23 thoughts on “How to test pipes in angular”

  1. Basic setup for pipe testing:

    import { Pipe } from './pipe.pipe';
    
    describe('Pipe', () => {
      let pipeToTest: Pipe;
    
      // synchronous beforeEach
      beforeEach(() => {
        pipeToTest = new Pipe();
      });
    
      it('should be instanciated', () => {
        expect(pipeToTest).toBeDefined();
      });
    });
    
    Reply

Leave a Comment