角茉莉花TypeError:无法读取null的属性'transform'

时间:2020-01-09 12:10:03

标签: angular angular6 pipe karma-jasmine transform

我正在尝试用星标测试管道,但得到.two-row-two-column mat-grid-tile:nth-of-type(3) .serveroutput-pop::before, .two-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop::before, .two-row-three-column mat-grid-tile:nth-of-type(2) .serveroutput-pop::before, .one-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop::before { left: -397px; right: auto; } :无法读取TypeError的属性'transform'。

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

我搜索没有结果,我不知道,但是我也有类似的错误测试路由。在其他项目上,路由工作正常。 在路由时,错误是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,可能不确定我的测试是否有问题。

1 个答案:

答案 0 :(得分:2)

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

您可以摆脱afterEach方法,但应该在初始化beforeEach的位置添加starPipe方法,如下所示:

let starPipe: StarsPipe;

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