0

我有一个简单的 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.valuefixture.detectChanges()

我究竟做错了什么?

这是一个plnkr

4

1 回答 1

1

像您这样的接缝还需要像这样发送“输入”事件:

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

这是在分叉 Plunkr中修复的完整测试

于 2017-08-28T19:59:56.590 回答