Angular unit test input value
Just add
fixture.detectChanges();
fixture.whenStable().then(() => {
// here your expectation
})
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()
.