表单上的Angular End to end组件测试失败

时间:2017-08-28 15:55:39

标签: angular jasmine angular-forms

我有一个简单的Angular表单,想要通过端到端测试来测试它。即我想从UI开始测试。我写的测试不能像我期望的那样工作。

组件:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
    selector: 'app-foo',
    template: `
    <form [formGroup]="form">
    <input id="foo" type="text" formControlName="foo">
    <button id="submit" type="submit">Submit</button>
    </form>`
})
export class FooComponent implements OnInit {

    form: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            foo: ['', [Validators.required, Validators.pattern('[0-9]+')]]
        });
    }
}

测试:

import { FooComponent } from './foo.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { By } from '@angular/platform-browser';

fdescribe('Foo component', () => {

    let component: FooComponent;
    let fixture: ComponentFixture<FooComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ReactiveFormsModule, FormsModule],
            declarations: [FooComponent]
        });
        fixture = TestBed.createComponent(FooComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
    });

    it('should have a valid foo when input is valid', () => {
        let foo = fixture.debugElement.query(By.css("#foo"));
        foo.nativeElement.value = "12345";
        fixture.detectChanges();
        expect(component.form.controls.foo.valid).toBeTruthy();
    });

});

测试失败:Expected false to be truthy.。虽然我事先执行了12345,但component.form.controls.foo.value值在调试到此篇文章时并未显示为fixture.detectChanges()的值。

我做错了什么?

Here's a plnkr

1 个答案:

答案 0 :(得分:1)

像你这样的接缝也需要发送&#39;输入&#39;像这样的事件:

input.dispatchEvent(new Event('input'));

以下是forked Plunkr

中修复的完整测试