首页 > 解决方案 > 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.
    });
});

标签: angulartypescriptunit-testingangular-reactive-forms

解决方案


尝试使用这个

let form = fb.group({
speed : ['']
});
form.controls.speed.setValue('10');
expect(form.pristine).toBeFalsy();

如果你想检查错误,你可以这样写:

expect(form.controls.speed.valid).toBe(false);

推荐阅读