Angular unit test input value Angular unit test input value angular angular

Angular unit test input value


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().


Just add

fixture.detectChanges();fixture.whenStable().then(() => {  // here your expectation})


Use your expect/assert within the whenStable.then function like this:

component.label = 'blah';fixture.detectChanges();fixture.whenStable().then(() => {    expect(component.label).toBe('blah');}