gpt4 book ai didi

javascript - 将初始值设置为 Angular 表单组以进行测试

转载 作者:行者123 更新时间:2023-12-02 03:23:59 29 4
gpt4 key购买 nike

我正在为 Angular 7 响应式(Reactive)表单编写一个单元测试,该表单的输入值预先填充了 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 预先填充数据吗?

最佳答案

调用fixture.detectChanges();将调用ngOnInit(),但user属性未定义。您可以像这样更改代码:

fixture = TestBed.createComponent(UserListItemComponent);
component = fixture.componentInstance;
const user = {
//your properties here
};
component.user = user;
fixture.detectChanges();

关于javascript - 将初始值设置为 Angular 表单组以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959642/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com