<spyOn>:找不到可以监视的对象

问题描述 投票:0回答:2

我有一个简单的组件:

.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()

知道出了什么问题吗?

angular karma-runner karma-jasmine
2个回答
3
投票

通过更新修复:

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

至:

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

0
投票

确保您已编写 XService = TestBed.inject(XService);在之前的每个。

这解决了我的错误

© www.soinside.com 2019 - 2024. All rights reserved.