Test an Angular2 Pipe that has a constructor method in Jasmine

后端 未结 1 886
北恋
北恋 2021-01-19 00:24

I am falling at the first hurdle testing an Angular Pipe that has a constructor.

My Pipe is as follows:

reverse.pipe.ts

import {
  Iterable         


        
相关标签:
1条回答
  • 2021-01-19 00:57

    I was very nearly there with my updated test. You do not need to provide IterableDiffers:

    reverse.pipe.spec.ts

    import { IterableDiffers } from '@angular/core';
    import { TestBed, inject } from '@angular/core/testing';
    
    import { ReversePipe } from './reverse.pipe';
    
    describe('ReversePipe', () => {
      it('should create an instance', inject([ IterableDiffers ], (iterableDiffers: IterableDiffers) => {
        const pipe = new ReversePipe(iterableDiffers);
    
        expect(pipe).toBeTruthy();
      }));
    
      it('should reverse the array of type Array<number>', inject([ IterableDiffers ], (iterableDiffers: IterableDiffers) => {
        const array = [ 1, 2, 3 ];
        const pipe = new ReversePipe(iterableDiffers);
    
        expect(pipe.transform(array)).toEqual([ 3, 2, 1 ]);
      }));
    
      it('should reverse the array of type Array<string>', inject([ IterableDiffers ], (iterableDiffers: IterableDiffers) => {
        const array = [ 'apple', 'banana', 'clementine' ];
        const pipe = new ReversePipe(iterableDiffers);
    
        expect(pipe.transform(array)).toEqual([ 'clementine', 'banana', 'apple' ]);
      }));
    });
    

    I also noticed I had an unnecessary if statement in reverse.pipe.spec.ts:

    // TODO: Throw an error if `array` isn't an Array
    if (Array.isArray(array) === false) return [];
    

    The first argument of transform would always be an Array; of course, the TypeScript compiler would throw a TypeError if the argument was anything other than an Array.

    For completeness my Pipe is:

    reverse.pipe.ts

    import {
      IterableDiffer,
      IterableDiffers,
      Pipe,
      PipeTransform
    } from '@angular/core';
    
    @Pipe({
      name: 'reverse',
      pure: false
    })
    export class ReversePipe implements PipeTransform {
    
      private cached: Array<any>;
      private differ: IterableDiffer<Array<any>>;
    
      constructor(private differs: IterableDiffers) {
        this.differ = this.differs.find([]).create(null);
      }
    
      public transform(array: Array<any>): Array<any> {
        const changes = this.differ.diff(array);
    
        if (changes) this.cached = array.slice().reverse();
    
        return this.cached;
      }
    }
    
    0 讨论(0)
提交回复
热议问题