angular - Angular 6 单元测试:以反应形式改变原始状态
问题描述
最近很抱歉,如果它与任何问题重复。我没有找到任何解决我的问题的方法。
所以我有一个带有一个输入字段的表单。当我在其中获取数据时,onInit
我将值放在该字段中并使其原始。在我手动更改值后,表格变得脏了,我做了一些动作。
它在组件中工作,但我无法正确测试它。在我setValue()
输入输入字段后,它保持原始状态(在测试中)。但我需要模拟真实的输入和原始形式应该变成false
.
组件.ts
ngOnInit() {
this.form = this.fb.group({
speed: this.fb.control(null)
});
this.service.getData().pipe(takeUntil(this.destroyed$))
.subscribe(info => {
this.info = info;
this.updateForm();
});
}
updateForm() {
this.form.patchValue({
speed: this.info.speed
});
this.form.get('speed').setValidators([
Validators.required,
Validators.pattern('^[0-9]*$'),
]);
this.form.markAsPristine();
}
组件.spec.ts
beforeEach(() => {
fixture = TestBed.createComponent(component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy(); // passed
});
it('should make form dirty', () => {
component.info = generateInfo();
fixture.detectChanges();
component.updateForm();
fixture.whenStable().then(() => {
expect(component.form.pristine).toBeTruthy();
expect(component.form.get('speed').value).toBe(20);
component.form.controls['speed'].setValue(10);
expect(component.form.pristine).toBeFalsy(); //error Expected true to be falsy.
});
});
解决方案
尝试使用这个
let form = fb.group({
speed : ['']
});
form.controls.speed.setValue('10');
expect(form.pristine).toBeFalsy();
如果你想检查错误,你可以这样写:
expect(form.controls.speed.valid).toBe(false);
推荐阅读
- sql - 在python中查询多个postgres表
- django - 使用 Django 的 Elelastic Beanstalk 上的 WSGI 问题
- php - PHP & jQuery 表单提交问题
- linux - libgnutls28-dev:apt 正在搜索错误的文件?
- c# - 如何获取要在身份验证请求正文中返回的属性?
- c - 如何在 C 中编写正确的包含和模块化我的应用程序?
- javascript - 发布到数据库不起作用(错误/警告:JSON 输入意外结束)
- python-3.x - Tensorflow 说层 conv2d 的 Input 0 与层不兼容:expected ndim=4, found ndim=3
- google-app-engine - 云构建 API
- python - django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id