[英]angular 5 karma unit test: Failed: Cannot read property childcomponent property ( itgroup) of undefined
我正在嘗試為在子組件中有一些依賴性的父組件方法編寫測試用例。
我收到以下錯誤。
失敗:無法讀取未定義的屬性“itGroup”,這是我的子組件屬性。
下面是我的代碼片段。
子組件。
child component: --------------- ---------------- interventionGroup: FormGroup; constructor() { } ngOnInit() { this.itGroup = new FormGroup({ test1: new FormControl(''), test2: new FormControl(''), }); }
父組件。
Parent Component mehod where i use the child component instance using view child ---------------------------- changeVal= false; submitted() { this.isValidTemplate = this.dynamicTemplateComponent.itGroup.invalid; if (this.isValidTemplate) { //logic } else { //logic } onChange(event){ this.changeval = true; } test case for method which have the child component instance which is showing undefined: --------------------------------------- it('on submit hit service', async () => { component.onChange(event); component.changeval = true; component.submitted(); const spy= spyOn(component, 'submitted'); let button = fixture.debugElement.nativeElement.querySelector('#submitbutton'); button.click(); fixture.detectChanges(); expect(component.submitted).toBeTruthy(); });
<form [formGroup]="TemplateGroup" class="edjustMargin" style="margin-top:20px; width:700px"> <div class="row"> <div> <div class="col-sm-6"> <label class="labelStyle ">dropdown:</label> <p-dropdown placeholder="Select val" class="" [options]="Options" formControlName="dropdown" (onChange)="change($event)"></p-dropdown> </div> <div *ngIf="changeVal"> <app-dynamic-template ></app-dynamic-template> </div> <div *ngIf="changeVal"> <button class="floating" id="submitbutton" type="submit" pButton (click)="submitted()" label="Submit"></button> <button class="floating" *ngIf="fromPDialog" type="submit" pButton (click)="cancelled()" label="Cancel"></button> <button class="floating" type="submit" pButton (click)="resetClicked()" label="Clear"></button> </div> </form>
你能告訴我你的整個測試嗎?
並且要處理您的子組件,請確保將您的子組件放在您的declarations
數組中。
import { ChildComponent } from 'childComponent';
...
let component: ThisComponet;
let childComponent: ChildComponent;
.....
declarations: [ChildComponent],
.....
component = fixture.componentInstance;
// to get a handle on the child component, you can select it By.directive
childComponent = fixture.debugElement.query(By.directive(ChildComponent)).componentInstance;
// should have access to your childComponent public properties and methods now
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.