簡體   English   中英

故障單元測試角度的反應形式字段

[英]trouble unit testing reactive form fields in angular

我正在使用 @angular/cli 1.0.0-beta.30 學習 Angular 2 和單元測試,並且在測試表單字段有效性的一個方面取得了一些成功,但不是全部。 我暫時在我的組件中使用內聯模板來暫時消除一層復雜性(單獨文件中的表單模板引入了異步性,對嗎?)。

ngOnInit()定義了一個name屬性,其中包括“required”和“minLength”的驗證器。 目前,一個空的表單字段將正確觸發“required”驗證器,但不會觸發“minLength”驗證器。 測試中的name.errors數組根本不包含對 required 的任何引用, 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"
    });

});

回答你的問題

name.errors['minLength']返回undefined,minLength是否需要異步處理?

您可以只檢查表單中的特定錯誤

expect(form.control.hasError('emailInvalid', ['email'])).toBe(true);

下面是一個完整的測試

// 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();

        name.setValue("");
        expect(name.hasError('required')).toBeTruthy();

        name.setValue("A");
        expect(name.hasError('minLength')).toBeTruthy();
    });

});
expect(name.hasError('minlength', ['minlength'])).toEqual(false);

試試這個對我有用

我相信這是因為您正在尋找的驗證密鑰是“minlength”非駝峰式,請注意小寫“l”。 我個人遇到過這個名字奇怪的錯誤屬性。

'minLength'的處理方式與 'required' 或任何其他驗證器(例如 maxLength、pattern)相同。

除非您的 signup-form.component.ts 代碼被截斷,否則我相信您會遺漏一些東西。

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

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

您還需要使用適當的鍵填充 formErrors 對象。

formErrors = {
  'name': ''
 }

並提供驗證消息。

validationMessages = {
  'name': {
    'required': 'Name is required.',
    'minlength': 'Name must be at least 2 characters long.'
  }
 }
expect(errors['minlength']).toBeTruthy();

這是由於 Validator.required 優先級,當存在此類錯誤時 - 其他驗證器甚至不會被調用並且不會產生其他錯誤。 您需要設置一些不正確的值來測試該特定部分:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM