Angular Jasmine/Karma错误,无法读取未定义的属性

Angular Jasmine/Karma错误,无法读取未定义的属性,angular,unit-testing,jasmine,karma-jasmine,Angular,Unit Testing,Jasmine,Karma Jasmine,我试图创建覆盖所有行(Jasmine/Karma),但我得到了错误,因为无法读取未定义的属性“搜索” 这是我的组件代码代码 public search() { if (this.searchCompany.length) { let term = this.searchCompany; this.tempList = this.tempNameList.filter(tag => { if (tag.companyName.toLowerCase().ind

我试图创建覆盖所有行(Jasmine/Karma),但我得到了错误,因为无法读取未定义的属性“搜索”

这是我的组件代码代码

public search() {
  if (this.searchCompany.length) {
    let term = this.searchCompany;
    this.tempList = this.tempNameList.filter(tag => {
      if (tag.companyName.toLowerCase().indexOf(term.toLowerCase()) > -1) {
        return tag;
      }
    });
  } else {
    this.resetCompanies();
  }
}
以下是我尝试过的spec的代码:

it('should search the data', () => {
  component.search;
  expect(component.search()).toBeUndefined();
});

我在这里做错了什么?

因为您的搜索方法有if语句-我们至少可以编写两个单元测试

本例适用于没有搜索标记的情况-如果我们有空的
searchCompany
,我们希望将调用
resetcompanys

  it('should resetCompanies if search is empty', () => {
    component.searchCompany = '';
    spyOn(component, 'resetCompanies').and.callFake(() => null);

    component.search();

    expect(component.resetCompanies).toHaveBeenCalled();
  });
这一个是针对搜索标记和搜索工作的情况-我们期望
templast
数组最终将由一个项目
{companyName:'test'}
,因为我们的搜索标记
test
匹配过滤器逻辑中的条件:

  it('should search company', () => {
    component.searchCompany = 'test';
    component.tempList = [];
    component.tempNameList = [
      { companyName: 'abc' },
      { companyName: 'test' },
      { companyName: 'def' },
    ];

    component.search();

    expect(component.tempList).toEqual([{ companyName: 'test' }]);
  });

你想达到什么目标?测试配置在哪里?为什么
component.search
?您甚至没有像
component.search()
那样正确调用该方法。感谢您的回复,我将在第三行中覆盖整个代码覆盖范围,我希望在哪里调用component.search()…您可以显示您的测试配置吗?还创建了一个,您也可以检查一下,非常感谢@Sherlock一个问题,因此对于我必须创建Spyon的每个if条件,在这种情况下-您可以使用
beforeach
jasmine函数,在每次测试之前可以初始化测试配置。我已经更新了,您可以看到
beforeach