【问题标题】:component property failing unit test despite being defined尽管已定义,组件属性仍未通过单元测试
【发布时间】:2017-11-02 17:58:07
【问题描述】:

我正在尝试为我创建的组件编写单元测试。不幸的是,我们正在测试一个字段,它在 HTML 中出现undefined,尽管我给了它一个同名的虚拟字段。在我的例子中,mastheadConfig 出现在 undefined

这是组件:

import { Component, OnInit, Input } from '@angular/core';

import { IMastheadConfig } from 'lib-components';

@Component({
  selector: 'app-shell',
  templateUrl: './shell.component.html',
  styleUrls: ['./shell.component.scss']
})
export class ShellComponent implements OnInit {

  public mastheadConfig: IMastheadConfig;

  constructor() { }

  ngOnInit() { }
}

这是 HTML:

<div>
  <masthead [config]="mastheadConfig">

    <!--This is where the error occurs-->
    <div *ngIf="mastheadConfig.customContent">
      <ng-content></ng-content>
    </div>

  </masthead>
  </div>
</div>

和测试文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { IMastheadConfig } from 'lib-components';

import { ShellComponent } from './shell.component';

fdescribe('ShellComponent', () => {
  let component: ShellComponent;
  let fixture: ComponentFixture<ShellComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ShellComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ShellComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    component.mastheadConfig = {
      avatar: {
        name: 'Namey McNameFace'
      },
      customContent: false,
      search: true,
      clientLogo: {
        type: 'icon',
        iconClass: 'icon'
      },
      actions: []
    };
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should tests input', () => {
    console.log("mastheadConfig: " + component.mastheadConfig);
    expect(component.mastheadConfig).toBeDefined();
  });
});

测试本身似乎没有失败——但是当我运行测试时,两个测试都得到TypeError: Cannot read property 'customContent' of undefined

我做错了什么?

【问题讨论】:

  • fixture.detectChanges(); 之前你已经设置了值。这在现实生活中应该来自哪里?
  • 老实说,这是从angular-cli 生成的,所以我没有多想。我删除了那行,现在测试通过了。请发表您的评论作为答案。
  • 您能否解释一下导致问题的原因?

标签: angular unit-testing


【解决方案1】:

mastheadConfig.customContent 表达式暗示有mastheadConfig 组件属性。如果不存在,那么

TypeError: 无法读取未定义的属性“customContent”

被抛出。

fixture.detectChanges() 触发更改检测并导致在设置 mastheadConfig 组件属性之前计算表达式。

相反,它应该是:

  beforeEach(() => {
    fixture = TestBed.createComponent(ShellComponent);
    component = fixture.componentInstance;

    component.mastheadConfig = {...};

    fixture.detectChanges();
  });

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 2021-08-06
    • 2020-01-17
    • 2022-08-22
    • 2021-01-22
    • 2019-03-26
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多