组件属性尽管已定义,但仍未通过单元测试

时间:2017-11-02 17:58:08

标签: angular unit-testing

我正在尝试为我创建的组件编写单元测试。不幸的是,有一个我们正在测试的字段,它在HTML中出现undefined,尽管我给它一个同名的虚拟字段。在我的情况下,它显示mastheadConfig的{​​{1}}。

以下是组件:

undefined

这是HTML:

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() { }
}

和测试文件:

<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(); }); }); 两个测试。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

  

TypeError:无法读取未定义

的属性'customContent'

被抛出。

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

相反,它应该是:

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

    component.mastheadConfig = {...};

    fixture.detectChanges();
  });