angularkarma-runnerkarma-jasmine

<spyOn> : could not find an object to spy upon


I have a simple component:

.html:

<h1>
  {{title}}
</h1>

<button (click)="changeTitle()">Change title</button>

.ts:

export class AppComponent {
  title = 'app works!';

  changeTitle() {
    this.title = 'New Title!';
  }
}

spec:

import {TestBed, async} from '@angular/core/testing';

import { AppComponent } from './app.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(AppComponent);
      component = fixture.componentInsance;
    });
  }));

  it('should create the app', async(() => {
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have as title 'app works!'`, async(() => {
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app works!');
  }));

  it('should render title in a h1 tag', async(() => {
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));

  it('should change the title to `New Title!`', async(() => {
    fixture.detectChanges();
    spyOn(component, 'changeTitle').and.callThrough();
    const compiled = fixture.debugElement.nativeElement;

    const button = compiled.querySelector('button');
    button.click();
    return fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(compiled.querySelector('h1').textContent).toBe('New Title!');
    });
  }));

});

The first 3 tests are passing, the last one returns Error: <spyOn> : could not find an object to spy upon for changeTitle()

Any idea what's wrong?


Solution

  • Fixed by updating:

    spyOn(component, 'changeTitle').and.callThrough();
    

    to:

    jasmine.createSpy('changeTitle').and.callThrough();