0
votes

I am trying to test a Pipe with stars, but i get TypeError: Cannot read property 'transform' of null.

import { StarsPipe } from './stars.pipe';

fdescribe('StarsPipe', () => {
    const inputStars = [
      { 'stars': 5 },
      { 'stars': 4 },
      { 'stars': 3 }
    ];

    afterEach(() => {
        starPipe = null;
    });

    let starPipe: StarsPipe = null;

    it('pipe for five stars', () => {
        const fivestars = starPipe.transform(inputStars, true, false, false);
        const expectedResult = [{ 'stars': 5 }];

        expect(fivestars).toEqual(expectedResult);
    });

    it('pipe for four stars', () => {
        const fourstars = starPipe.transform(inputStars, false, true, false);
        const expectedResult = [{ 'stars': 4 }];

        expect(fourstars).toEqual(expectedResult);
    });

    it('pipe for three stars', () => {
        const threestars = starPipe.transform(inputStars, false, false, true);
        const expectedResult = [{ 'stars': 3 }];

        expect(threestars).toEqual(expectedResult);
    });
});

The Pipe is this:

import { Pipe, PipeTransform } from '@angular/core';
import { Room } from './room';

@Pipe({
  name: 'stars',
  pure: true
})
export class StarsPipe implements PipeTransform {
    filter = {
        five: true,
        four: true,
        three: true
    };
    transform(rooms: Array < Room > , five: boolean, four: boolean, three: boolean): any[] {
        if (five === true) {
            return rooms.filter(x => (x.stars === 5));
        } else if (four === true) {
            return rooms.filter(x => (x.stars === 4));
        } else if (three === true) {
            return rooms.filter(x => (x.stars === 3));
        } else {
            return null;
        }
    }
}    

I searched with no result, i do not know about it, but i have a similar error testing routing too. On other Projects routing works fine. On routing the error is debugElement of undefined, maybe there is a problem on my testing, not sure.

1

1 Answers

2
votes

When running the tests, starPipe is null because it is not properly initialized. Therefore, invoking starPipe.transform produces this error.

You can get rid of the afterEach method but should add a beforeEach method instead where you initialize starPipe as follows:

let starPipe: StarsPipe;

beforeEach(() => {
    starPipe = new StarsPipe(); 
});