首页 > 解决方案 > Angular Jasmine TypeError:无法读取 null 的属性“转换”

问题描述

我正在尝试用星星测试管道,但我得到TypeError:无法读取属性“转换” 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;
        }
    }
}    

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

标签: angularangular6pipekarma-jasminetransform

解决方案


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

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

let starPipe: StarsPipe;

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

推荐阅读