【问题标题】:Jasmine / Karma error as cannot read property of undefinedJasmine / Karma 错误,因为无法读取未定义的属性
【发布时间】:2021-03-14 18:01:04
【问题描述】:

我正在尝试创建覆盖所有行(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();
  }
}

这是我尝试过的规范的以下代码:

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

我在这里做错了什么?

【问题讨论】:

  • 你想达到什么目的?测试配置在哪里?为什么component.search?你甚至没有像component.search()那样正确调用方法。
  • 感谢您的回复,我想在第三行覆盖整个代码覆盖率,我期望在哪里调用 component.search() ...
  • 你能展示你的测试配置吗?

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

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

这是在没有搜索标签的情况下使用的——如果我们有空的searchCompany,我们希望resetCompanies会被调用:

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

    component.search();

    expect(component.resetCompanies).toHaveBeenCalled();
  });

这是针对我们有搜索标签并且搜索工作的情况 - 我们预计 tempList 数组最终将由一项 { 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' }]);
  });

【讨论】:

  • 还创建了stackblitz demo,你也检查一下
  • 非常感谢@Sherlock 一个问题,所以对于每一个 if 条件我都必须创建 SpyOn
  • 在这种情况下 - 你可以使用beforeEach jasmine 函数,你可以在每次测试之前初始化你的测试配置。
  • 我已经更新了stackblitz example,你可以看到beforeEach的使用示例
猜你喜欢
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
  • 2019-02-11
  • 2023-03-29
  • 1970-01-01
  • 2019-02-07
相关资源
最近更新 更多