首页 > 解决方案 > 编辑父组件表单时如何测试角度子组件显示

问题描述

这个子组件是保存按钮组件。所以我想做的是确保在表单输入字段值发生更改时出现保存按钮。

我可以确认它可以获取form.invalid = false,并且form.dirty = true在表单名称值更改后,但子组件永远不会显示,仍然saveBtnComp = null, btnElmsAfterEdit = []

为什么子组件从不显示?

在 parent.component.html

<div>
  <save-button-component
    *ngIf="form.dirty"
    [invalid]="form.invalid"
    (saveChangesEvent)="submit()"
    (cancelEvent)="reset()"
  ></save-button-component>
</div>

在测试用例

beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    component.value ={
       name: 'John Doe',
       age: '20'
    };
    component.ngOnInit();
    fixture.detectChanges();
});

it('Save Button shows when form is edited', async(() => {

   // before edit form value
   const saveBtnBeforeEdit = fixture.debugElement.nativeElement.querySelector('save-button-component');

   expect(saveBtnBeforeEdit).toBeNull();

   const name = getControl('name');
   name.setValue('Stan Hansen');
   name.markAsDirty();
   fixture.detectChanges();


   // after edit form value
   fixture.whenStable().then(() => {

       const saveBtnAfterEdit = fixture.debugElement.nativeElement.querySelector('save-button-component');

       expect(saveBtnAfterEdit).not.toBeNull();

   });
}));

function getControl(...path: string[]): FormControl {
    return component.form.get(path) as FormControl;
}

标签: angularunit-testingangular-material

解决方案


我解决了这个问题。

我将 component.ngOnInit() 移动到 beforeEach();

我更新了我的代码。


推荐阅读