angular - 编辑父组件表单时如何测试角度子组件显示
问题描述
这个子组件是保存按钮组件。所以我想做的是确保在表单输入字段值发生更改时出现保存按钮。
我可以确认它可以获取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;
}
解决方案
我解决了这个问题。
我将 component.ngOnInit() 移动到 beforeEach();
我更新了我的代码。
推荐阅读
- python - 使密码 NumericValidator 可选
- python - Python 在 Windows 中使用“:”在标题中创建目录
- java - 设置连续渲染(假)。没有动作动画
- r - R (xlsx) - 根据列值从 DF 写入多个 Excel 文件
- angular - Angular:中止 POST 请求
- macos - 使用 pfx 证书在 macos 上签署电子应用程序
- python - 将数据框中的元素从字符串转换为浮点数
- javascript - html url输入在句子后禁用键盘自动空格(移动)
- facebook - Appcelerator - 当我尝试使用 Titanium SDK 7.2.0 GA 在 Facebook 上分享时出错
- python - 在 sqlalchemy 选择对象中测试 where 子句