我正在为Angular 7反应性表单编写单元测试,该表单的输入值已预先在ngInit上填充服务器数据。如何设置此表单的值,以便在测试过程中不会给我五个“未定义值”错误?
这是我在ngOnInit上预先填写的表单:
ngOnInit() {
this.userForm = this.formBuilder.group({
id: [ this.user.id ],
first_name: [this.user.first_name, Validators.required],
last_name: [this.user.last_name, Validators.required],
});
这是表单的当前(准系统)测试代码:
//import modules
describe('UserListItemComponent', () => {
let component: UserListItemComponent;
let fixture: ComponentFixture<UserListItemComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MaterialModule,
ReactiveFormsModule,
FormsModule,
],
declarations: [
UserListItemComponent,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserListItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
component.userForm.setValue({
id: 123,
first_name: "john",
last_name: "smith",
});
expect(component).toBeTruthy();
});
});
但是,因果报应测试人员仍然说它是id的未定义。是因为它没有用setValue
预填充数据吗?
答案 0 :(得分:0)
调用fixture.detectChanges();
将调用ngOnInit()
,但是user
属性是未定义的。您可以这样更改代码:
fixture = TestBed.createComponent(UserListItemComponent);
component = fixture.componentInstance;
const user = {
//your properties here
};
component.user = user;
fixture.detectChanges();
答案 1 :(得分:0)
测试时,您可以具有更新表单值的功能:
function updateForm(id: string, first_name: string, last_name: string) {
component.userForm.controls['id'].setValue(id);
component.userForm.controls['first_name'].setValue(first_name);
component.userForm.controls['last_name'].setValue(last_name);
}
在测试案例中:
it('should create form', () => {
updateForm('1','john','smith');
expect(component).toBeTruthy();
expect(component.userForm.value).toBeTruthy();
});
或者您可以使用以下方法将user
对象传递给组件:
`component.user = mockUser;`
并且表单值将在Init上设置。
很可能是由于组件上未定义的user
属性导致的错误。