简体   繁体   English

Angular-专注于按钮的单元测试

[英]Angular - Unit testing focusing on button

I am attempting to unit test whether my button has been focused on, but I cannot seem to get the spy to work correctly? 我正在尝试进行单元测试,以确保按钮是否专注于我,但似乎无法让间谍正常工作?

I saw [this post][1], but it hasn't helped fully. 我看到了[这篇文章] [1],但是并没有完全帮助您。

Am I missing something obvious? 我是否缺少明显的东西?

component.ts component.ts

ngOnInit() {
    // autofocus on the cancel button to guard against mistakes
    document.getElementById('cancel').focus();
  }

The focus is flawed to start with. 首先,重点是有缺陷的。

When using Angular, you should not use document to fetch your elements. 使用Angular时,不应使用document来获取元素。

Use a viewChild instead. 请改用viewChild。

@ViewChild('cancel') cancelButton: ElementRef<HtmlButtonElement>;
ngAfterViewInit() {
  this.cancelButton.nativeElement.focus();
}

Now your test looks like this 现在你的测试看起来像这样

it('should focus cancel button', () => {
  spyOn(component.cancelButton.nativeElement, 'focus');
  component.ngAfterViewInit();
  expect(component.cancelButton.nativeElement.focus).toHaveBeenCalledWith();
});

EDIT If you still want to use your way, consider using By.css() : 编辑如果您仍然想使用自己的方式,请考虑使用By.css()

it('should autofocus on cancel button on init', () => {
  const cancelButton = fixture.debugElement.query(By.css('#cancel'));
  spyOn(cancelButton, 'focus');
  component.ngOnInit();
  expect(cancelButton.focus).toHaveBeenCalled();
});

Recall ngOnInit() after your spy has been created in your spec, as pointed by @trichietrichie 如规范@trichietrichie所示,在您的规范中创建spy之后,请调用ngOnInit()

Also, take advantage of fixture instead of relying on document to fetch html elements. 同样,利用fixture而不是依赖document来获取html元素。

beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ ConfirmationComponent ],
      providers: [ MessageService]
    });

    fixture = TestBed.createComponent(ConfirmationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();    
    component.ngOnInit();
  });

  it('should autofocus on cancel button on init', () => {
    const cancelButton = fixture.debugElement.query(By.css('#cancel'));
    spyOn(cancelButton.nativeElement, 'focus'); // create spy here   
    component.ngOnInit();
    expect(cancelButton.focus).toHaveBeenCalled();
  });

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

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