可以使用Angular提供的FormControl和FormGroup来测试输入字段是否正确地更改了值。我们可以创建一个FormGroup并将FormControl绑定到输入字段上,在测试中,我们可以模拟外部输入并通过断言来验证输入字段是否正确更新。示例代码:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule ],
declarations: [ MyComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
// create FormGroup
component.myForm = new FormGroup({
myInput: new FormControl('')
});
});
it('should change input field value correctly based on external input', () => {
// simulate external input
component.myForm.get('myInput').setValue('New value');
// assert input field value
const inputElement = fixture.nativeElement.querySelector('input');
expect(inputElement.value).toEqual('New value');
});
});