angular - 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;
}
}
}
我搜索没有结果,我不知道,但我也有类似的错误测试路由。在其他项目路由工作正常。在路由错误是debugElement
,undefined
也许我的测试有问题,不确定。
解决方案
运行测试时,starPipe
是null
因为它没有正确初始化。因此,调用starPipe.transform
会产生此错误。
您可以摆脱该afterEach
方法,但应添加一个beforeEach
方法,而不是在您初始化的地方starPipe
,如下所示:
let starPipe: StarsPipe;
beforeEach(() => {
starPipe = new StarsPipe();
});
推荐阅读
- swift - 如何在 Xcode swift 5 中制作视频循环?
- python - 当训练数据是图像时,Keras model.fit() 中的“批次”是什么
- bash - 参数扩展以删除具有多个模式的字符串
- javascript - 如何使用 Discord.js 从另一个文件中读取命令?
- laravel - Laravel URL Helper 返回 IP 地址而不是域名
- python - Python len() 函数未返回原始长度,因为我的映射列表包含一些重复项
- google-apps-script - 使用 Google Script 将 TD Ameritrade 开发者应用程序中的股票报价加载到表格中
- javascript - Puppeteer 标识符字符串变量不会解析;不确定为什么
- scala - Java库中的Scala类型不匹配
- postgresql - AdonisJS - 从数组中更新许多项目