2017-02-09 88 views
0

我正在使用@ angular/cli 1.0.0-beta.30學習Angular 2和單元測試,並且有一點成功測試了表單字段有效性的一個方面,但並非全部。我在我的組件中使用了內聯模板,暫時去除了一層複雜性(單獨文件中的表單模板引入了異步性,是正確的?)。問題單元測試角度反應性表單字段

ngOnInit()定義了一個name屬性,其中包含「required」和「minLength」的驗證器。目前,一個空的表單字段將正確地觸發「必需的」驗證器,但不會觸發「minLength」驗證器。 name.errors陣列在測試中根本不包含任何需要的參考,name.errors['minLength']返回undefined。 minLength是否需要異步處理?我無法找到符合我的問題的文檔或示例。

// signup-form.component.ts 
... 
export class SignupFormComponent implements OnInit { 

    user: FormGroup; 

    constructor(private fb: FormBuilder) { 
    } 

    ngOnInit() { 
     this.user = this.fb.group({ 
      name: ['', [Validators.required, Validators.minLength(2)]], 
      account: this.fb.group({ 
       email: ['', Validators.required, Validators.pattern("[^ @]*@[^ @]*")], 
       confirm: ['', Validators.required] 
      }) 
     }) 
    } 

    onSubmit({ value, valid }: { value: User, valid: boolean }) { 
     console.log(value, valid); 
    } 

} 

我測試

// signup-form.component.spec.ts 
import { SignupFormComponent } from './signup-form.component'; 

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

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

    beforeEach(() => { 
     fixture = TestBed.createComponent(SignupFormComponent); 
     component = fixture.componentInstance; 
     component.ngOnInit(); 
     fixture.detectChanges(); 
    }); 

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

    it('form invalid when empty',() => { 
     expect(component.user.valid).toBeFalsy(); 
    }); 

    it('name field validity',() => { 
     let name = component.user.controls['name']; 
     expect(name.valid).toBeFalsy(); 

     let errors = {}; 
     name.setValue(""); 
     errors = name.errors || {}; 
     expect(errors['required']).toBeTruthy(); // this works 
     expect(errors['minLength']).toBeTruthy(); // this fails, "undefined" 
    }); 

}); 

回答

0

'的minLength' 作爲 '必要' 或以相同的方式被處理的任何其他驗證器(例如最大長度,圖案)。

除非您的signup-form.component.ts代碼被截斷,否則我相信您錯過了幾件事情。

在您的FormBuilder中,您需要訂閱數據更改。 this.user.valueChanges.subscribe(data => this.onValueChanged(data));

然後你需要聲明onValueChanged函數。請參閱Angular Form Validation cookbook以獲得通用的onValueChanged函數。

您還需要使用適當的鍵填充formErrors對象。
formErrors = { 'name': '' }

並提供validationMessages。
validationMessages = { 'name': { 'required': 'Name is required.', 'minlength': 'Name must be at least 2 characters long.' } }