kostjaigin
kostjaigin

Reputation: 185

SpyOn SideNav does not find given method

I have a side navigation menu in my test project and i want to write a simple test to check that the sidenav opens (toggles) when i click the button. The AppComponent itself references to sidebar via its dependency sidenavbar.

it('when button is clicked, sidenav appears', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;
    let sidenav_button = fixture.debugElement.nativeElement.querySelector('button');
    fixture.detectChanges();
    expect(component.sidenavbar.opened).toBeFalsy();
    spyOn(component.sidenavbar, 'toggle');
    sidenav_button.click();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.sidenavbar.toggle).toHaveBeenCalled();
  });

right now it says, the method toggle() does not exist to spy on it. I am pretty sure it actually does.

Upvotes: 0

Views: 374

Answers (1)

AliF50
AliF50

Reputation: 18869

It could be that toggle is private and you can't spy on it.

sidenavbar is an object within AppComponent, correct? It's not a child component?

If I were you, I would just see the opened property changed.

it('when button is clicked, sidenav appears', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;
    let sidenav_button = fixture.debugElement.nativeElement.querySelector('button');
    fixture.detectChanges();
    expect(component.sidenavbar.opened).toBeFalsy();
    // spyOn(component.sidenavbar, 'toggle');
    sidenav_button.click();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.sidenavbar.opened).toBeTruthy();
  });

Upvotes: 1

Related Questions