角度:无法测试属性指令

时间:2019-08-08 05:17:26

标签: angular testbed

这是我设计的一项指令,旨在防止意外单击按钮。

@Directive({
    selector: '[myDebounceClick]'
})
export class DebounceClickDirective {
    clicked: boolean = false;

    @HostListener('click', ['$event'])
    clickEvent() {
      if (this.clicked) {
        return false;
      } else {
        this.clicked = true;
        setTimeout(() => {
          this.clicked = false;
        }, 1500);
      }
    }
}

这是我的测试套件

class PageObject {
  public button: DebugElement;

  constructor(private fixture: ComponentFixture<TestComponent>) {
    fixture.detectChanges();
    this.button = fixture.debugElement.query(By.directive(DebounceClickDirective));
  }

  clickButton(): void {
    this.button.triggerEventHandler('click', null);
    this.fixture.detectChanges();
  }

  get clickSpy() {
    return this.fixture.componentInstance.onClick;
  }
}

@Component({
  template: `<button myDebounceClick (click)="onClick()">Click me</button>`
})
class TestComponent {
  onClick = jasmine.createSpy('onClick');
}

fdescribe('DebounceClickDirective', () => {
  let pageObj: PageObject;
  beforeEach(() => {
    const fixture = TestBed.configureTestingModule({
      declarations: [ DebounceClickDirective, TestComponent ]
    })
    .createComponent(TestComponent);
    pageObj = new PageObject(fixture);
  });

  it('should test button becomes disabled after first click', fakeAsync(() => {
    pageObj.clickButton();
    tick(600);
    pageObj.clickButton();
    tick(2000);

    expect(pageObj.clickSpy).toHaveBeenCalledTimes(1);
  }));
});

我的问题是按钮可以通过Web界面工作,即使我的量角器测试也可以正常工作,但是,单元测试始终失败,因为单击了2次按钮而不是单击了2次。我错了吗?

我还尝试删除fakeAsynctick的呼叫并替换return false;与preventDefaultstopPropagation一起使用,但没有任何效果。

0 个答案:

没有答案