【问题标题】:<spyOn> : could not find an object to spy upon<spyOn> : 找不到要监视的对象
【发布时间】:2017-11-30 06:47:36
【问题描述】:

我有一个简单的组件:

.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: &lt;spyOn&gt; : could not find an object to spy upon for changeTitle()

知道有什么问题吗?

【问题讨论】:

    标签: angular karma-runner karma-jasmine


    【解决方案1】:

    通过更新修复:

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

    到:

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

    【讨论】:

    • 你能解释一下你为什么这样做吗?它实际上是在监视你的方法吗?无论谁对答案投了反对票,你能解释一下原因吗?你有什么顾虑吗?你有更好的解决方案吗? Jasmine 网站上的文档说:当没有监视功能时,jasmine.createSpy 可以创建一个“裸”的间谍。这个间谍充当任何其他间谍 - 跟踪调用、参数等。但它背后没有实现。间谍是 JavaScript 对象,可以这样使用。在您的情况下,您确实具有监视功能。
    • 我非常讨厌这样的问题,因为@JanatbekSharsheyev 的所有担忧正是我来这里要解决的问题!
    • @JanatbekSharsheyev 评论解释了为什么这不是答案。该测试只是确保您创建了一个不相关的模拟间谍来调用,而不是您调用了您的代码
    • 我不明白为什么这个答案甚至被接受。这可能是一种解决方法,但不是我们正在寻找的答案。为什么我要创建一个裸间谍?在我的情况下,我也有一个方法,我知道它的实现。 @JanatbekOrozaly,我没有否决任何答案,但我想对这个问题有一个正确的答案。请帮忙。
    • 没有读完,但似乎这里回答了类似的问题:stackoverflow.com/questions/40106801/…
    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多