繁体   English   中英

如何在Angular 6中使用Jasmine将加载的数据测试为反应形式?

[英]How do I test loaded data into a reactive form with Jasmine in Angular 6?

我有一个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);
    }
}

测试总是无法说出表单中的值是空。 有人知道我在做什么错吗? 谢谢!

这是详细的分配:

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

我尚未测试此代码,但我认为您要尝试执行的操作确实很接近。

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);
}


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM