我在用角度6进行单元测试时遇到问题。我正在尝试使用一个input()
参数来测试一个简单的组件。问题是我不知道如何继续。执行ng test
时收到错误消息:
TypeError:无法读取未定义的属性“ id_profile”
我的代码是这样:
模型
export class Profile {
id_profile: string;
name: string;
}
html
<div class="card" (click)="clicked()">
<div id="profile">{{profile.id_profile}}</div>
<i class="material-icons">vpn_key</i>
</div>
组件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { Profile } from 'app/models';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.scss']
})
export class ProfileComponent {
@Input() profile: Profile;
private profileShown: Profile;
constructor(public router: Router) {
}
OnInit() {
this.profileShown= this.profile;
}
clicked() {
this.profileShown= this.profile;
this.router.navigate(['pages']);
}
}
最后,我的测试:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ProfileComponent} from './profile.component';
describe('ProfileComponent', () => {
let component: ProfileComponent;
let fixture: ComponentFixture<ProfileComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ProfileComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
component.profile= {
'id_profile': '12345678A',
'name': 'SUMUM_D',
};
fixture.detectChanges();
expect(component).toBeTruthy();
});
});
我该怎么做才能解决此问题?我在做正确的事吗?预先感谢
答案 0 :(得分:2)
在将数据设置为detectChanges
属性之前,请勿运行@Input()
,因为它会渲染视图并为未初始化的属性引发错误。
beforeEach(() => {
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
// fixture.detectChanges(); -- Remove this line
});
答案 1 :(得分:0)
请让我知道它是否仍然显示错误
it('should create', () => {
component.profileShown= {
'id_profile': '12345678A',
'name': 'SUMUM_D',
};
fixture.detectChanges();
expect(component).toBeTruthy();
});