如何在Angular2中对FormControl进行单元测试

问题描述 投票:16回答:1

我正在测试的方法如下:

/**
   * Update properties when the applicant changes the payment term value.
   * @return {Mixed} - Either an Array where the first index is a boolean indicating
   *    that selectedPaymentTerm was set, and the second index indicates whether
   *    displayProductValues was called. Or a plain boolean indicating that there was an 
   *    error.
   */
  onPaymentTermChange() {
    this.paymentTerm.valueChanges.subscribe(
      (value) => {
        this.selectedPaymentTerm = value;
        let returnValue = [];
        returnValue.push(true);
        if (this.paymentFrequencyAndRebate) { 
          returnValue.push(true);
          this.displayProductValues();
        } else {
          returnValue.push(false);
        }
        return returnValue;
      },
      (error) => {
        console.warn(error);
        return false;
      }
    )
  }

正如您所看到的,paymentTerm是一个返回Observable的表单控件,然后对其进行订阅并检查返回值。

我似乎无法找到有关单元测试FormControl的任何文档。我最接近的是这篇关于模拟Http请求的文章,这是一个类似的概念,因为它们正在返回Observables,但我不认为它完全适用。

作为参考,我使用Angular RC5,使用Karma运行测试,框架是Jasmine。

unit-testing angular jasmine angular2-forms angular2-testing
1个回答
33
投票

首先让我们通过测试组件中的异步任务来解决一些常见问题。当我们测试测试不受控制的异步代码时,我们应该使用fakeAsync,因为它允许我们调用tick(),这使得操作在测试时看起来是同步的。例如

class ExampleComponent implements OnInit {
  value;

  ngOnInit() {
    this._service.subscribe(value => {
      this.value = value;
    });
  }
}

it('..', () => {
  const fixture = TestBed.createComponent(ExampleComponent);
  fixture.detectChanges();
  expect(fixture.componentInstance.value).toEqual('some value');
});

当调用ngOnInit时,此测试将失败,但Observable是异步的,因此该值不会及时设置为测试中的同步调用(即expect)。

为了解决这个问题,我们可以使用fakeAsynctick强制测试等待所有当前的异步任务完成,使测试看起来像是同步的。

import { fakeAsync, tick } from '@angular/core/testing';

it('..', fakeAsync(() => {
  const fixture = TestBed.createComponent(ExampleComponent);
  fixture.detectChanges();
  tick();
  expect(fixture.componentInstance.value).toEqual('some value');
}));

现在测试应该通过,因为Observable订阅没有意外延迟,在这种情况下我们甚至可以在tick调用tick(1000)中传递毫秒延迟。

这个(fakeAsync)是一个有用的特征,但问题是当我们在templateUrls中使用@Component时,它会进行XHR调用,而XHR calls can't be made in a fakeAsync。在某些情况下,您可以模拟服务以使其同步,如this post中所述,但在某些情况下,它只是不可行或太难。在表格的情况下,这是不可行的。

出于这个原因,在使用表单时,我倾向于将模板放在template而不是外部templateUrl中,如果它们非常大(只是在组件文件中没有大字符串),则将表单分成更小的组件。我能想到的唯一另一个选择是在测试中使用setTimeout,让异步操作通过。这是一个偏好问题。我刚决定在使用表单时使用内联模板。它打破了我的应用程序结构的一致性,但我不喜欢setTimeout解决方案。

现在,就形式的实际测试而言,我发现的最好的来源只是看看source code integration tests。您需要将标记更改为您正在使用的Angular版本,因为默认主分支可能与您使用的版本不同。

以下是一些例子。

当测试输入你想要的是更改nativeElement上的输入值,并使用input发送dispatchEvent事件。例如

@Component({
  template: `
    <input type="text" [formControl]="control"/>
  `
})
class FormControlComponent {
  control: FormControl;
}

it('should update the control with new input', () => {
  const fixture = TestBed.createComponent(FormControlComponent);
  const control = new FormControl('old value');
  fixture.componentInstance.control = control;
  fixture.detectChanges();

  const input = fixture.debugElement.query(By.css('input'));
  expect(input.nativeElement.value).toEqual('old value');

  input.nativeElement.value = 'updated value';
  dispatchEvent(input.nativeElement, 'input');

  expect(control.value).toEqual('updated value');
});

这是从源集成测试中获得的简单测试。下面是更多的测试示例,一个是从源代码中获取的,另外一个不是,只是为了显示测试中没有的其他方法。

对于您的特定情况,看起来您正在使用(ngModelChange),您将其分配给onPaymentTermChange()。如果是这种情况,那么您的实现没有多大意义。当价值发生变化时,(ngModelChange)已经会吐出一些东西,但每次模型改变时你都会订阅。你应该做的是接受更改事件发出的$event参数

(ngModelChange)="onPaymentTermChange($event)"

每次更改时,您都会传递新值。所以只需在您的方法中使用该值,而不是订阅。 $event将是新的价值。

如果你想在valueChange上使用FormControl,你应该开始在ngOnInit中听它,所以你只订阅了一次。你会在下面看到一个例子。我个人不会去这条路。我会按照您的方式进行,但不是订阅更改,只需接受更改中的事件值(如前所述)。

这是一些完整的测试

import {
  Component, Directive, EventEmitter,
  Input, Output, forwardRef, OnInit, OnDestroy
} from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser/src/dom/debug/by';
import { getDOM } from '@angular/platform-browser/src/dom/dom_adapter';
import { dispatchEvent } from '@angular/platform-browser/testing/browser_util';
import { FormControl, ReactiveFormsModule } from '@angular/forms';

class ConsoleSpy {
  log = jasmine.createSpy('log');
}

describe('reactive forms: FormControl', () => {
  let consoleSpy;
  let originalConsole;

  beforeEach(() => {
    consoleSpy = new ConsoleSpy();
    originalConsole = window.console;
    (<any>window).console = consoleSpy;

    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule ],
      declarations: [
        FormControlComponent,
        FormControlNgModelTwoWay,
        FormControlNgModelOnChange,
        FormControlValueChanges
      ]
    });
  });

  afterEach(() => {
    (<any>window).console = originalConsole;
  });

  it('should update the control with new input', () => {
    const fixture = TestBed.createComponent(FormControlComponent);
    const control = new FormControl('old value');
    fixture.componentInstance.control = control;
    fixture.detectChanges();

    const input = fixture.debugElement.query(By.css('input'));
    expect(input.nativeElement.value).toEqual('old value');

    input.nativeElement.value = 'updated value';
    dispatchEvent(input.nativeElement, 'input');

    expect(control.value).toEqual('updated value');
  });

  it('it should update with ngModel two-way', fakeAsync(() => {
    const fixture = TestBed.createComponent(FormControlNgModelTwoWay);
    const control = new FormControl('');
    fixture.componentInstance.control = control;
    fixture.componentInstance.login = 'old value';
    fixture.detectChanges();
    tick();

    const input = fixture.debugElement.query(By.css('input')).nativeElement;
    expect(input.value).toEqual('old value');

    input.value = 'updated value';
    dispatchEvent(input, 'input');
    tick();

    expect(fixture.componentInstance.login).toEqual('updated value');
  }));

  it('it should update with ngModel on-change', fakeAsync(() => {
    const fixture = TestBed.createComponent(FormControlNgModelOnChange);
    const control = new FormControl('');
    fixture.componentInstance.control = control;
    fixture.componentInstance.login = 'old value';
    fixture.detectChanges();
    tick();

    const input = fixture.debugElement.query(By.css('input')).nativeElement;
    expect(input.value).toEqual('old value');

    input.value = 'updated value';
    dispatchEvent(input, 'input');
    tick();

    expect(fixture.componentInstance.login).toEqual('updated value');
    expect(consoleSpy.log).toHaveBeenCalledWith('updated value');
  }));

  it('it should update with valueChanges', fakeAsync(() => {
    const fixture = TestBed.createComponent(FormControlValueChanges);
    fixture.detectChanges();
    tick();

    const input = fixture.debugElement.query(By.css('input')).nativeElement;

    input.value = 'updated value';
    dispatchEvent(input, 'input');
    tick();

    expect(fixture.componentInstance.control.value).toEqual('updated value');
    expect(consoleSpy.log).toHaveBeenCalledWith('updated value');
  }));
});

@Component({
  template: `
    <input type="text" [formControl]="control"/>
  `
})
class FormControlComponent {
  control: FormControl;
}

@Component({
  selector: 'form-control-ng-model',
  template: `
    <input type="text" [formControl]="control" [(ngModel)]="login">
  `
})
class FormControlNgModelTwoWay {
  control: FormControl;
  login: string;
}

@Component({
  template: `
    <input type="text"
           [formControl]="control" 
           [ngModel]="login" 
           (ngModelChange)="onModelChange($event)">
  `
})
class FormControlNgModelOnChange {
  control: FormControl;
  login: string;

  onModelChange(event) {
    this.login = event;
    this._doOtherStuff(event);
  }

  private _doOtherStuff(value) {
    console.log(value);
  }
}

@Component({
  template: `
    <input type="text" [formControl]="control">
  `
})
class FormControlValueChanges implements OnDestroy {
  control: FormControl;
  sub: Subscription;

  constructor() {
    this.control = new FormControl('');
    this.sub = this.control.valueChanges.subscribe(value => {
      this._doOtherStuff(value);
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

  private _doOtherStuff(value) {
    console.log(value);
  }
}

UPDATE

至于关于异步行为的这个答案的第一部分,我发现你可以使用等待异步任务的fixture.whenStable()。因此无需仅使用内联模板

it('', async(() => {
  fixture.whenStable().then(() => {
    // your expectations.
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.