Angular unit test input value

Zyga picture Zyga · Dec 9, 2016 · Viewed 85.5k times · Source

I have been reading official Angular2 documentation for unit testing (https://angular.io/docs/ts/latest/guide/testing.html) but I am struggling with setting a component's input field value so that its reflected in the component property (bound via ngModel). The screen works fine in the browser, but in the unit test I cannot seem to be able to set the fields value.

I am using below code. "fixture" is properly initialized as other tests are working fine. "comp" is instance of my component, and the input field is bound to "user.username" via ngModel.

it('should update model...', async(() => {
    let field: HTMLInputElement = fixture.debugElement.query(By.css('#user')).nativeElement;
    field.value = 'someValue'
    field.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(field.textContent).toBe('someValue');
    expect(comp.user.username).toBe('someValue');
  }));

My version of Angular2: "@angular/core": "2.0.0"

Answer

Paul Samsotha picture Paul Samsotha · Dec 9, 2016

Inputs don't have textContent, only a value. So expect(field.textContent).toBe('someValue'); is useless. That's probably what's failing. The second expectation should pass though. Here's a complete test.

@Component({
  template: `<input type="text" [(ngModel)]="user.username"/>`
})
class TestComponent {
  user = { username: 'peeskillet' };
}

describe('component: TestComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [ TestComponent ]
    });
  });

  it('should be ok', async(() => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      let input = fixture.debugElement.query(By.css('input'));
      let el = input.nativeElement;

      expect(el.value).toBe('peeskillet');

      el.value = 'someValue';
      el.dispatchEvent(new Event('input'));

      expect(fixture.componentInstance.user.username).toBe('someValue');
    });
  }));
});

The important part is the first fixture.whenStable(). There is some asynchronous setup with the forms that occurs, so we need to wait for that to finish after we do fixture.detectChanges(). If you are using fakeAsync() instead of async(), then you would just call tick() after fixture.detectChanges().