【发布时间】:2019-05-26 08:16:22
【问题描述】:
我正在为 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();
});
});
但是,Karma 测试运行器仍然说它对于 id 是未定义的。是不是因为没有用setValue预填充数据?
【问题讨论】:
标签: javascript angular unit-testing