为@Input函数angular 2创建测试规范

时间:2016-10-17 07:55:15

标签: unit-testing angular karma-jasmine

    @Input()
    public set isRunning(value: boolean) {
        if (!value) {
            this.cancelTimeout();
            this.isDelayedRunning = false;
            return;
        }

        if (this.currentTimeout) {
            return;
        }

        this.currentTimeout = setTimeout(() => {
            this.isDelayedRunning = value;
            this.cancelTimeout();
        }, this.delay);
    }

上面的代码是角度为2的组件的@Input。我在为输入创建测试用例时遇到问题,因为我不知道如何为这种输入创建测试。我应该创造一个吸气剂吗?我该怎么做呢?我找不到任何参考资料。

1 个答案:

答案 0 :(得分:1)

使用setter(set),您所做的只是将值赋给属性(方法)

let fixture = TestBed.createComponent(TestComponent);
let component = fixture.componentInstance;l
component.isRunning = true;
fixture.detectChanges();

对于超时,您可能需要执行类似

的操作
import { fakeAsync } from '@angular/core/testing;

it('should change isDelayedRunning', fakeAsync(() => {
  let fixture = TestBed.createComponent(TestComponent);
  let component = fixture.componentInstance;
  fixture.detectChanges();

  component.isRunning = true;
  // wait for timeout
  tick(200);
  fixture.detectChanges();
  expect(fixture.componentInstance.isDelayedRunning).toBe(true);
}));
如果您在组件中使用fakeAsync,则

templateUrl无法正常工作。所以你必须使用async。但是AFAIK,我们可以控制等待期间没有tick这样的设施,所以你可能只需要在测试中设置超时

import { async } from '@angular/core/testing';

it('should change isDelayedRunning', async(() => {
  let fixture = TestBed.createComponent(TestComponent);
  let component = fixture.componentInstance;
  fixture.detectChanges();

  component.isRunning = true;
  setTimeout(() => {
    fixture.detectChanges();
    expect(fixture.componentInstance.isDelayedRunning).toBe(true);
  }, 200);
}));