【问题标题】:Angular Jasmine TypeError: Cannot read property 'transform' of nullAngular Jasmine TypeError:无法读取 null 的属性“转换”
【发布时间】:2020-01-09 12:10:03
【问题描述】:

我正在尝试用星号测试管道,但我得到 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);
    });
});

管道是这样的:

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,可能我的测试有问题,不确定。

【问题讨论】:

    标签: angular angular6 pipe karma-jasmine transform


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2021-11-24
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多