unit-testing - 为什么在 Angular 10 单元测试中没有将 FormControl 标记为脏?
问题描述
以下测试在 Angular 9 中通过,但在 Angular 10 中失败。为什么?
升级-test.component.html:
<input [formControl]="formControl" />
升级-test.component.ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-upgrade-test',
templateUrl: './upgrade-test.component.html'
})
export class UpgradeTestComponent {
formControl: FormControl = new FormControl(0);
}
升级-test.component.spec.ts:
import { TestBed } from '@angular/core/testing';
import { UpgradeTestComponent } from './upgrade-test.component';
import { ReactiveFormsModule } from '@angular/forms';
describe('Test', () => {
TestBed.configureTestingModule({
declarations: [UpgradeTestComponent],
imports: [ReactiveFormsModule],
});
it('should pass', () => {
const fixture = TestBed.createComponent(UpgradeTestComponent);
const component = fixture.componentInstance;
fixture.detectChanges();
expect(component.formControl.dirty).toBeFalsy();
component.formControl.patchValue(1);
const inputElem: HTMLInputElement = fixture.nativeElement.querySelector('input');
inputElem.dispatchEvent(new Event('change'));
fixture.detectChanges();
expect(component.formControl.dirty).toBeTruthy();
});
});
测试结果:
测试 ✗应该通过 期望假为真。 在用户上下文。(http://localhost:9876/_karma_webpack_/src/app/components/upgrade-test/upgrade-test.component.spec.ts:21:41) 在 ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1) 在 ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292 :1) 在 ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:363:1)
解决方案
因为patchValue()
orsetValue()
方法不会改变dirty
控件或窗体的状态。
如果用户更改了 UI 中的值,则控件是脏的。
推荐阅读
- javascript - 处理Angular中自定义输入组件的标签点击
- r - R中从数据框到栅格的不规则网格
- c# - C#SqlParameter数组如何使用三元运算符有条件地将值设置为null
- javascript - Discord.js 消息用户对应用程序做出反应
- python - 如何使用 API 调用迭代字符串参数列表?
- node.js - 立即断开mongo连接(冒烟测试)
- python - Discord.py 自我机器人
- linux-kernel - 使用 bitbake 为 BBB 构建 .dtbo 覆盖
- visual-studio-code - Visual Studio 代码智能感知停止工作,不再有 CSS 选项卡选项或颜色选择器
- java - 带有信号量的生产者-消费者陷入僵局