Angular Testing: FormControl valueChanges Observable

前端 未结 1 1537
轻奢々
轻奢々 2021-01-04 07:20

I have a text input and I\'m listening for the changes.

component

name = new FormControl(\'\',Validators.required);

ngOnInit() {
           


        
相关标签:
1条回答
  • 2021-01-04 07:50

    At first glance I think you missed the fact that your FormControl is not connected to input because you're using FormControlName directive that takes control name as @Input.

    If you want to test FormControl then you can consider FormControlDirective that takes FormControl as @Input:

    <input name="name" [formControl]="name">
                                      ^^^^^
                          `name` is FormControl instance here not string
    

    Now we can be sure that whenever we change text in input your FormControl will fire changes. But as soon as you write such template angular will ask you for ReactiveFormsModule dependency in your test:

    import { ReactiveFormsModule } from '@angular/forms';
    ....
    
    TestBed.configureTestingModule({
       imports: [
         ReactiveFormsModule  <=== add this
       ],
       declarations: [TestComponent],
    });
    

    Now regarding your test.

    1) You must tell the TestBed to perform data binding by calling fixture.detectChanges():

    const fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges(); <== add this
    

    2) You should fire change on input correctly:

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

    Here's the whole code:

    it('should display original title', () => {
      const fixture = TestBed.createComponent(TestComponent);
      fixture.detectChanges();
      const app = fixture.debugElement.componentInstance;
      const el = fixture.nativeElement.querySelector('input');
      el.value = 'something';
      el.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      fixture.whenStable().then(() => {
        expect(app.data).toBe('newvalue');
      });
    });
    

    Plunker Example

    0 讨论(0)
提交回复
热议问题