Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在对FormGroup进行更改后,我如何触发单元测试中可观察的更改值?_Angular_Unit Testing_Angular Reactive Forms - Fatal编程技术网

Angular 在对FormGroup进行更改后,我如何触发单元测试中可观察的更改值?

Angular 在对FormGroup进行更改后,我如何触发单元测试中可观察的更改值?,angular,unit-testing,angular-reactive-forms,Angular,Unit Testing,Angular Reactive Forms,我正在一个组件上编写单元测试代码,该组件包括一个被动表单(FormGroup)和一个valueChanges订阅,但我还没有弄清楚如何确保valueChanges事件由FormGroup发出 // In the component under test: this.formGroup.get('field').valueChanges .subscribe((obj: any[]) => { debugger; // BREAKPOINT da

我正在一个组件上编写单元测试代码,该组件包括一个被动表单(FormGroup)和一个valueChanges订阅,但我还没有弄清楚如何确保valueChanges事件由FormGroup发出

// In the component under test:
this.formGroup.get('field').valueChanges
     .subscribe((obj: any[]) => {
         debugger; // BREAKPOINT
         dataObject.fieldValues = [ ... ];
         ... details here should be unimportant ...
     });

// In the unit test:
it('should set dataObject from field component', fakeAsync(() => {
        [
    values: string[] = [ ... ];

    component.formGroup.get('field').setValue(values);
    component.formGroup.get('field').updateValueAndValidity({ emitEvent: true });
    fixture.detectChanges();
    tick();

    expect(component.dataObject.fieldValues.length).toEqual(values.length);

}));


我无法使单元测试规范达到组件订阅代码中的断点。

您的
勾选()
夹具的顺序。detectChanges()
是关键

假设您在设置componentInstance的BeforeSearch循环中已经有了一个fixture.detectChnages(),那么您需要做的是:

首先调用tick(),这样测试将等待该值被设置。之后,您就可以像在expect中一样从组件内部访问该值。如果希望在模板内进行更改,则需要触发将组件与模板同步的
fixture.detectChanges

但重要的是,在fixture.detectChanges()之前调用
tick()


谢谢,我跟网上的一个例子走得太近了。这确实解决了我的问题。
// In the component under test:
this.formGroup.get('field').valueChanges
     .subscribe((obj: any[]) => {
         debugger; // BREAKPOINT
         dataObject.fieldValues = [ ... ];
         ... details here should be unimportant ...
     });

// In the unit test:
it('should set dataObject from field component', fakeAsync(() => {
        [
    values: string[] = [ ... ];

    component.formGroup.get('field').setValue(values);
    component.formGroup.get('field').updateValueAndValidity({ emitEvent: true });

    tick();
    fixture.detectChanges(); // OPTIONAL

    expect(component.dataObject.fieldValues.length).toEqual(values.length);

}));