【发布时间】: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