I am falling at the first hurdle testing an Angular Pipe that has a constructor.
My Pipe is as follows:
import {
Iterable
I was very nearly there with my updated test. You do not need to provide IterableDiffers
:
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:
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;
}
}