[英]Karma Input parameter unit testing
我在angular 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();
});
});
我該怎么做才能解決這個問題? 我在做正確的事嗎? 提前致謝
在將數據設置為@Input()
屬性之前,請不要運行detectChanges
,因為它會渲染視圖並為未初始化的屬性引發錯誤。
beforeEach(() => {
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
// fixture.detectChanges(); -- Remove this line
});
請讓我知道它是否仍然顯示錯誤
it('should create', () => {
component.profileShown= {
'id_profile': '12345678A',
'name': 'SUMUM_D',
};
fixture.detectChanges();
expect(component).toBeTruthy();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.