Skip to content

[testing] Testing a form #7229

@cexbrayat

Description

@cexbrayat

Let's say we have a very simple model-driven form:

@Component({..})
export class Register {

  login: Control;
  userForm: ControlGroup;

  constructor(fb: FormBuilder) {
    this.login = fb.control('', Validators.required);
    this.userForm = fb.group({
      login: this.login,
    });
  }
}

with a template:

<form (ngSubmit)="register()" [ngFormModel]="userForm">
    <input id="login" ngControl="login">
</form>

The following unit test would come to mind:

describe('Register Component', () => {

  let fixture: ComponentFixture;

  beforeEachProviders(() => []);

  beforeEach(injectAsync([TestComponentBuilder],
    (tcb: TestComponentBuilder) => tcb.createAsync(Register).then(f => fixture = f)
  ));

  it('should display a form to register', () => {

    // given a form
    let userForm = fixture.componentInstance.userForm;

    expect(userForm.valid).toBe(false);
    expect(userForm.find('login').getError('required')).toBe(true);

    // when adding values in the form
    let nativeElement = fixture.nativeElement;
    nativeElement.querySelector('input').value = 'Cédric';
    nativeElement.querySelector('input').dispatchEvent(new Event('input'));

    fixture.detectChanges();

    // then we should have a valid form, with no error
    expect(userForm.valid).toBe(true);
    expect(userForm.find('login').getError('required')).toBe(null);

  });

});

But the test will fail: after the detectChanges(), the form is still not valid.

I encountered this issue when I was writing my ebook with early alphas

The test is green with:

// when adding values in the form
let login = fixture.debugElement.query(By.css('input'));
login.nativeElement.value = 'Cédric';
login.nativeElement.dispatchEvent(new Event('input'));

Looks like it works with fixture.debugElement.query but not with fixture.nativeElement.querySelector.

Is that normal?

cc @juliemr @mhevery

Metadata

Metadata

Assignees

Labels

area: testingIssues related to Angular testing features, such as TestBed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions