physicsboy
physicsboy

Reputation: 6348

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.

Am I missing something obvious?

component.ts

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

Upvotes: 0

Views: 4640

Answers (2)

user4676340
user4676340

Reputation:

The focus is flawed to start with.

When using Angular, you should not use document to fetch your elements.

Use a viewChild instead.

@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() :

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();
});

Upvotes: 2

Amit Chigadani
Amit Chigadani

Reputation: 29745

Recall ngOnInit() after your spy has been created in your spec, as pointed by @trichietrichie

Also, take advantage of fixture instead of relying on document to fetch html elements.

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();
  });

Upvotes: 2

Related Questions