Jasmine TypeError:无法设置属性';搜索';未定义的
我已经搜索过了,但找不到我的问题的答案。我有一个Angular 5项目,我正在尝试运行我的单元测试,我得到了错误:Jasmine TypeError:无法设置属性';搜索';未定义的,jasmine,angular5,Jasmine,Angular5,我已经搜索过了,但找不到我的问题的答案。我有一个Angular 5项目,我正在尝试运行我的单元测试,我得到了错误: TypeError: Cannot set property 'search' of undefined TypeError: Cannot read property 'search' of null 这是我的ts文件: import { Component, OnChanges, OnInit, Input } from '@angular/core'; import {
TypeError: Cannot set property 'search' of undefined
TypeError: Cannot read property 'search' of null
这是我的ts文件:
import { Component, OnChanges, OnInit, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CheckboxModule } from '@common-web-components';
import { ItemFilter } from '../../models/item-filter';
import { ItemBrandSearchResponse } from '../../models/item-brand-search-response';
import { ItemBrandSearchResponseService } from '../../services/item-brand-search-response.service';
@Component({
selector: 'app-item-brand-filter',
templateUrl: './item-brand-filter.component.html',
styleUrls: ['./item-brand-filter.component.css']
})
export class ItemBrandFilterComponent implements OnInit, OnChanges {
@Input()
filter: ItemFilter;
availableCount: number;
firstOpen: Boolean = true;
searching: Boolean = true;
itemBrands = new Array<ItemBrandSearchResponse>();
constructor(private itemBrandSearchResponseService: ItemBrandSearchResponseService) { }
ngOnInit() {
this.searching = true;
this.firstOpen = false;
this.getItemBrandForFilter();
}
ngOnChanges() {
if (!this.firstOpen) {
this.searching = true;
this.getItemBrandForFilter();
}
}
getItemBrandForFilter(): void {
this.itemBrandSearchResponseService.get(this.filter).subscribe(
results => {
this.itemBrands = results.data;
if (results.availableCount) {
this.availableCount = results.availableCount;
}
this.searching = false;
},
error => {
console.error('Error getting items');
}
);
}
getRouterLink(): string {
return this.filter.search === '' ? '/items' : '/items/search/' + this.filter.search;
}
}
我犯了一个错误:
TypeError: Cannot set property 'search' of undefined
TypeError: Cannot read property 'search' of null
所以我搜索了一下,发现一篇文章说我需要设置它。现在我遇到了这个新错误,真的找不到任何适合的解决方案。我找到了我的解决方案。在测试环境中,我的component.filter尚未初始化 所以我补充说:
component.filter = new ItemFilter();
这解决了我的问题。现在很明显 “为什么单元测试比实际编码花费的时间更长?”——对此我有很多答案。1.测试是实际的编码。2.如果你有好的代码,写测试是很快的——事实上,一旦你练习了,写测试通常比不写测试要快。3.几乎所有人类设计的东西都需要比设计更多的测试,不仅仅是软件。“一旦你实践了”是最好的短语!我已经编写了30多年了,但在过去的4-5年中,我最终只在代码中执行单元测试,直到最近,我还从未在前端代码中执行过单元测试。我为部署而构建的代码工作得非常好。问题是我需要如何设置我的规范文件以便Jasmine运行。你在哪里初始化的?有着同样的问题,得出了同样的结论,但似乎仍然无法让它发挥作用。