Angular Jasmine TypeError: Cannot read property 'transform' of null

Angular Jasmine TypeError: Cannot read property 'transform' of null

我正在尝试用星星测试管道,但我得到 TypeError:无法读取 null 的 属性 'transform'。

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);
    });
});

管道是这样的:

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;
        }
    }
}    

我搜索没有结果,我不知道,但我也有类似的错误测试路由。在其他项目中,路由工作正常。 路由错误是debugElement of undefined,可能是我测试有问题,不确定。

当运行测试时,starPipenull,因为它没有正确初始化。因此,调用 starPipe.transform 会产生此错误。

您可以删除 afterEach 方法,但应该添加一个 beforeEach 方法,而不是在初始化 starPipe 的地方,如下所示:

let starPipe: StarsPipe;

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