Lev
Lev

Reputation: 15734

testing that a component method calls another method

Given this simple component :

import { Component} from '@angular/core';

@Component({
  selector: 'app-component'
})
export class AppComponent {
  foo() {
    this.bar();
  }

  bar() {
    console.log('hello');
  }
}

How come the following test won't validate that bar is called when I call foo

describe('AppComponent', () => {
  let component: AppComponent;

    beforeEach(() => {
    component = new AppComponent();
  }

  it('should foobar', () => {
    component.foo();
    spyOn(component, 'bar');
    expect(component.bar).toHaveBeenCalled();
  })

}

I get the failed test :

Expected spy bar to have been called.

Upvotes: 41

Views: 59379

Answers (2)

Tino Jose Thannippara
Tino Jose Thannippara

Reputation: 782

it("should foobar", () => {
    const spy = spyOn(component, "bar");
    component.foo();
    expect(spy).toHaveBeenCalled();
  });

Upvotes: 8

Teddy Sterne
Teddy Sterne

Reputation: 14219

You need to set up the spy before the method is called. Jasmine spys wrap function to determine when they are called and what they get called with. The method must be wrapped before the spied on method is called in order to capture the information. Try changing your test to match the following:

it('should foobar', () => {
    spyOn(component, 'bar');
    component.foo();
    expect(component.bar).toHaveBeenCalled();
})

Upvotes: 79

Related Questions