即使所有表单字段均有效,Angular Form也无效

时间:2019-10-04 05:34:21

标签: angular angular-reactive-forms angular-testing

我正在尝试解决一个角度形式验证 动手,为此我制作了以下形式,该形式通过了除一个以外的所有测试用例,看起来像问题出在测试文件(app.component.spec.ts)上,该文件仅可读 working Demo,显示表单状态为 VALID。,但失败测试

过去两天,我一直坚持使用此动手表格。我们非常感谢您的帮助

------------------- [只读]​​ app.component.spec.ts ----------

import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormControl, AbstractControl, FormGroup } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { asNativeElements, DebugElement } from '@angular/core';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule],
      declarations: [AppComponent]
    })
    .compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  }));

  // it('should create the component', () => {
  //   expect(component).toBeTruthy();
  // });

  it('form should be invalid when empty', () => {
    expect(component.contactForm.invalid).toBeTruthy();
  });

  it('form should be valid on entering required fields', () => {
    fixture.detectChanges(); // ngOninit()
    component.name.setValue('david');
    component.phone.setValue('9999999999');

    expect(component.contactForm.valid).toBeTruthy();
  });

  describe('#name', () => {
    let name: AbstractControl;

    beforeEach(() => {
      name = component.contactForm.controls['name'];
    });

    it('should be invalid if empty', () => {
      expect(name.invalid).toBeTruthy();
    });

    it('should be a "required" field', () => {
      expect(name.errors['required']).toBeTruthy();
    });

    it('should be valid if some value is present', fakeAsync(() => {
      name.setValue('david');
      expect(name.valid).toBeTruthy();
    }));
  });

  describe('#phone', () => {
    let phone: AbstractControl;
    beforeEach(() => {
      phone = component.contactForm.controls['phone'];
    });

    it('should be invalid if empty', () => {
      expect(phone.invalid).toBeTruthy();
    });

    it('should have "required" validation', () => {
      expect(phone.errors['required']).toBeTruthy();
    });

    it('should accept only numbers(pattern validation)', () => {
      phone.setValue('abc');
      expect(phone.errors['pattern']).toBeTruthy();
    });

    it('should have 10 digits(minlength & maxlength validation)', () => {
      phone.setValue('123');
      expect(phone.errors['minlength']).toBeTruthy();
      phone.setValue('12333333333');
      expect(phone.errors['maxlength']).toBeTruthy();
    });
  });

  describe('#address - zip', () => {
    let address;
    let zip;
    beforeEach(() => {
      address = component.contactForm.controls['address'] as FormGroup ;
      zip = address.controls['zip'] ;
      fixture.detectChanges(); // ngOnInit()
    });
    it('should be a number', fakeAsync(() => {
      zip.setValue('abc');
      expect(zip.errors['pattern']).toBeTruthy();
      zip.setValue('123456');
      fixture.detectChanges();
      expect(zip.valid).toBeTruthy();
    }));
    it('should have 6 digits exactly', () => {
      // enter 3 digits and check for minlength validation
      zip.setValue('123');
      expect(zip.errors['minlength']).toBeTruthy();

      // enter 7 digits and check for maxlength validation
      zip.setValue('1234567');
      fixture.detectChanges(); // update changes, angular will not do for you automatically
      expect(zip.errors['maxlength']).toBeTruthy();
    });
  });
});

这是测试错误

AppComponent
 ✖ form should be valid on entering required fields
   HeadlessChrome 75.0.3770 (Linux 0.0.0)
  Expected false to be truthy.
    at UserContext. (src/app/app.component.spec.ts:35:41)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:359:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke 
 (node_modules/zone.js/dist/zone-testing.js:308:1)
       at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:358:1)

3 个答案:

答案 0 :(得分:4)

您的测试专家失败,因为zip没有值,但是需要一个值。要么删除zip属性的验证,要么在测试中提供一个值。

在AppComponent中删除对zip的验证看起来像这样

contactForm = new FormGroup({
        name: new FormControl(null, [ Validators.required,
                                    Validators.minLength(4),
                                    Validators.maxLength(10)]),
        phone: new FormControl(null,  [ Validators.required,
                                        Validators.pattern("^[0-9]*$"),        Validators.minLength(10),
                                        Validators.maxLength(10) ]),
        address: new FormGroup({
        street: new FormControl(null),
        city: new FormControl(null),
        zip: new FormControl(null)
        })
    });

在测试中传递zip值看起来像这样

    it('form should be valid on entering required fields', () => {
        fixture.detectChanges(); // ngOninit()
        component.name.setValue('david');
        component.phone.setValue('9999999999');
        component.zip.setValue('123456');

        expect(component.contactForm.valid).toBeTruthy();
      });

仅当组件中具有这些属性的设置器时,第二个选项才有效。在您的堆叠闪电战中,只有吸气剂。

答案 1 :(得分:0)

将这段代码添加到app.component.ts

contactForm = new FormGroup({

  name: new FormControl(null,[ 
  Validators.required,
  Validators.minLength(4),
  Validators.maxLength(10)]),                        
  phone: new FormControl(null,[
  Validators.required,
  Validators.pattern("^[0-9]*$"),
  Validators.minLength(10),
  Validators.maxLength(10) ]),
                                        
  address: new FormGroup({
    street: new FormControl(null),
    city: new FormControl(null),
    zip: new FormControl(null,[ 
    Validators.minLength(6),
    Validators.maxLength(6),
    Validators.pattern('^[0-6]*$')])
    })
});

答案 2 :(得分:0)

如果你想检查你的表单是否有效,这意味着是否为空,那么你应该使用。 this.formData.valid(); 在这种方法中,如果您的表单无效,您会收到回复,然后您会收到错误消息,否则,您会收到正确的回复。