首页 > 解决方案 > 为什么在 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)

标签: unit-testingangular-reactive-formsangular10

解决方案


因为patchValue()orsetValue()方法不会改变dirty控件或窗体的状态。

如果用户更改了 UI 中的值,则控件是脏的。

https://angular.io/api/forms/AbstractControl#dirty


推荐阅读