Search code examples
angularkarma-jasmineangular-test

How to check the length of a returned array from a pipe in an angular test?


I have a pipe that filters a given array for a keyword and returns any matches. In this example the keyword 'Music' should return 3 results. How can I check in my test to see if it returns 3 results? Is it possible to do without making a copy of dummyData[] with only the elements that contain the keyword 'Music'?

test.spec.ts

describe('ArrayFilterPipe', () => {

    let pipe: ArrayFilterPipe;

    const dummyData = [
      {id: 1, name: 'Rap Music'},
      {id: 2, name: 'Hip Hop'},
      {id: 3, name: 'Country Music'},
      {id: 4, name: 'Radio Stations'},
    ];

    it('the keyword "Music" should return 3 results', () => {
        expect(pipe.transform(dummyData, 'Music')).toEqual(); // Is it possible to check the length or do I have to create a copy of dummyData with only the elements that contain 'Music'?
    });

 }

ArrayFilterPipe

export class ArrayFilterPipe implements PipeTransform {

  transform(data[], keyword: string) {
    keyword = keyword.toLowerCase();
    return data.filter(x => {
      return x.name.toLowerCase().includes(keyword);
    });
  }
}

Solution

  • You're not creating an instance or ArrayFilterPipe anywhere. Once you create an instance of ArrayFilterPipe, you can check for the length like below

    describe('ArrayFilterPipe', () => {
        const pipe = new ArrayFilterPipe();
    
        const dummyData = [
            { id: 1, name: 'Rap Music' },
            { id: 2, name: 'Hip Hop' },
            { id: 3, name: 'Country Music' },
            { id: 4, name: 'Radio Stations' },
        ];
    
        it('the keyword "Music" should return 2 results', () => {
            expect(pipe.transform(dummyData, 'Music').length).toEqual(2);
        });
    });
    

    Also, as per the dummyData you are providing, it should return 2 results not 3.