web-dev-qa-db-ja.com

<spyOn>:スパイするオブジェクトが見つかりませんでした

私は単純なコンポーネントを持っています:

.html:

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

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

.ts:

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

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

スペック:

_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!');
    });
  }));

});
_

最初の3つのテストは合格です。最後のテストはError: <spyOn> : could not find an object to spy upon for changeTitle()を返します

何が間違っているのでしょうか?

5
TheUnreal

更新して修正:

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

に:

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