Angular - 强制反应式表单在单元测试中有效

问题描述 投票:0回答:4

我正在使用 Angular v4.4.4。在组件中,单击模板中的按钮后,假设反应式表单有效,则保存表单。类似于(伪代码):

public onSave(): void {
    if (this.myForm.valid) {
        this._createFoo();
    }
}

private _createFoo(): void {
    this._fooService.createItem(this.foo).subscribe(result => {
        // stuff happens...
    });
}

在相关的单元测试中,我需要强制表单有效,以便我可以确认服务正在被调用。像这样的东西:

it('should create Foo', () => {
    const spy = spyOn(_fooService, 'createItem').and.callThrough();
    component.foo = new Foo();
    fixture.detectChanges();
    const bookButton = fixture.debugElement.query(By.css('#bookButton'));
    expect(bookButton !== null).toBeTruthy('missing Book button');
    bookButton.triggerEventHandler('click', null);
    expect(spy).toHaveBeenCalled();
});

这将失败,因为 myForm 从未设置为有效。

在这种特殊情况下,我不想为表单中的每个输入提供一个值。我只需要观察服务订阅是否发生。如何强制表格有效?

angular unit-testing angular-reactive-forms
4个回答
18
投票

为什么不直接清除验证者列表呢?

// If there are any async validators
//
this.myForm.clearAsyncValidators();
// If there are any normal validators
//
this.myForm.clearValidators();
// Doing the validation on all the controls to put them back to valid
//
this.formGroup.updateValueAndValidity();

这将确保您的表单没有验证器,从而有效。


7
投票

如果有人仍在为此苦苦挣扎:

正如@realappie答案所示,我们应该清除所有同步/异步验证器。 但在大多数情况下,验证器位于控件上,而不是表单本身。因此,只需循环所有控件对每个控件执行此操作即可。

从测试文件来看,它应该看起来像:

const controls = component.myForm.controls;

for (const control in controls) {
    // Clear sync validators - use clearAsyncValidators() for async
    // validators
    controls[control].clearValidators();
    // should update just the control and not everything
    controls[control].updateValueAndValidity({ onlySelf: true });
}
component.myForm.updateValueAndValidity();

5
投票

仅使用 javascript,你可以这样做:

      Object.defineProperty(comp.editForm, 'valid', {
        get: () => true
      });

覆盖 getter,始终返回 true。


3
投票

我们可以监视表单组的 valid 属性,而不是使表单有效。

我们可以这样做:

spyOnProperty(component.myForm, 'valid').and.returnValue(false);

每当访问表单组(this.myForm.valid)的valid属性时,这行代码都会返回

true
,这有助于通过测试。

© www.soinside.com 2019 - 2024. All rights reserved.