Javascript 角度4(karma)测试输入值到输入字段
我试图测试通过键盘输入的值。我的问题是在输入字段设置值之后,当我打印它时,它会打印,但当我在whenStable()中打印它时,它会打印为空。我想知道为什么这个值在Whitstable()函数中被重置。我怎样才能修好它 我已经提到:编写这个测试用例Javascript 角度4(karma)测试输入值到输入字段,javascript,angular,unit-testing,karma-jasmine,Javascript,Angular,Unit Testing,Karma Jasmine,我试图测试通过键盘输入的值。我的问题是在输入字段设置值之后,当我打印它时,它会打印,但当我在whenStable()中打印它时,它会打印为空。我想知道为什么这个值在Whitstable()函数中被重置。我怎样才能修好它 我已经提到:编写这个测试用例 it('Test input field value. ', async () => { const divDescription = fixture.debugElement.query(By.css('#costDescriptio
it('Test input field value. ', async () => {
const divDescription = fixture.debugElement.query(By.css('#costDescription'));
divDescription.nativeElement.value = 'text';
divDescription.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
fixture.whenStable().then(() => {
console.log('sendInput : ', divDescription.nativeElement.value); // prints ''
expect(divDescription.nativeElement.value).toContain('text');
});
});
您必须将更改检测呼叫移动到内部
it('Test input field value. ', async () => {
const divDescription = fixture.debugElement.query(By.css('#costDescription'));
divDescription.nativeElement.value = 'text';
divDescription.nativeElement.dispatchEvent(new Event('input'));
console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
fixture.whenStable().then(() => {
fixture.detectChanges(); // moved inside
console.log('sendInput : ', divDescription.nativeElement.value);
expect(divDescription.nativeElement.value).toContain('text');
});
});
删除WhenStable()可以实现这一点
it('Test input field value. ', async () => {
const divDescription = fixture.debugElement.query(By.css('#costDescription'));
divDescription.nativeElement.value = 'text';
divDescription.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(divDescription.nativeElement.value).toContain('text');
});
moving fixture.detectChanges()不起作用,但当我移除fixture.whenStable()时,测试用例通过了;谢谢你的回复。上面的代码如图所示工作,但是我应该在Jasmine runner中看到这个内容,它是Angular 7应用程序的宿主。字段值在浏览器中不会更改?嗯,这个测试实际上毫无意义,因为您所做的只是测试刚刚设置的值。更好的测试是确保输入字段中的更改也反映在模型中。