首页 > 解决方案 > 如何在 Angular 6 中使用 Jasmine 将加载的数据测试为反应形式?

问题描述

我有一个 Angular 6 应用程序,它使用ngrx从商店对象将数据加载到反应式表单中。我正在尝试对此进行单元测试,但似乎无论我如何更改我的表单对象,我分配的属性总是有空白值。

这是我的代码:

HTML

<form [formGroup]="myForm" novalidate>
    <input id="name" formControlName="name" />
    <input id="age" formControlName="age" />
</form>

零件

export interface MyObject {
    name: string;
    age: string;
}

export class MyObjectComponent {
    myObject: MyObject;
    myForm: FormGroup;

    constructor(private fb: FormBuilder, private store: Store<fromStore.State>) { }

    ngOnInit() {
        this.myForm = this.fb.group({
            name: [null, [Validators.required]],
            age: [null, [Validators.required]]
        });
        this.store.select(fromStore.getMyObject).subscribe(x => this.myForm.patchValue(x));
}

规格文件

describe('MyObjectComponent', () => {
    let component: MyObjectComponent;
    let fixture: ComponentFixture<MyObjectComponent>;
    let store: Store<fromStore.State>;
    let initialStateL MyObject;
    let el: DebugElement;

    beforeEach(async(() => {
        initialState = {
            name: 'My Name',
            age: 55
        };
        TestBed.configureTestingModule({
            imports: [
                FormsModule,
                ReactiveFormsModule,
                HttpClientModule,
                StoreModule.forRoot({}),
                StoreModule.forFeature('my-object', reducer)
            ],
            declarations: [MyObjectComponent],
            providers: []
        })
        .compileComponents().then(() => {
            fixture = TestBed.createComponent(MyObjectComponent);
            component = fixture.componentInstance;
            el = fixture.debugElement;
            spyOn(store, 'dispatch').and.callThrough();
            fixture.detectChanges();
        });
    }));

    it('should patch values into form', async(() => {
        expect(component.myForm.controls.age.value).toBe(55);
    }
}

测试总是失败,说表单中的值什么都不是。有人知道我在做什么错吗?谢谢!

标签: javascriptangularjasmineangular6

解决方案


这是详细的分配:

首先为表单创建模拟值,访问您的表单并分配值,然后您需要触发组件上的更改检测,最后测试输入的值。

我还没有测试这段代码,但我认为你想要做什么真的很接近。

describe('MyObjectComponent', () => {

// Rest of code...

it('should patch values into form', async(() => {
    // Mock value
    const mock_age_value = 55;

    fixture = TestBed.createComponent(DualityAccordionTabComponent);
    const compiled = fixture.componentInstance;

    // Value assignation
    compiled.myForm.patchValue({
       age: mock_age_value
    });

    // Trigger change detection
    fixture.detectChanges();

    expect(component.myForm.controls.age.value).toBe(55);
}


}

推荐阅读