2017-06-27 45 views
0

我有一个简单的组件来窥探:<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()

任何想法有什么不对?

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

到:

回答

-1

通过更新修正

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

你能解释一下你为什么要这样的,是它在你的方法实际上是间谍? 和谁downvoted答案你可以解释为什么?你有什么担忧吗?你有更好的解决方案吗? 茉莉花网站的文档说:当没有可以窥探的功能时,jasmine.createSpy可以创建一个“裸”的间谍。这个间谍像其他间谍追踪调用,参数等一样起作用,但其背后没有任何实施。间谍是JavaScript对象,可以这样使用。 在你的情况下,你确实有一个窥探的功能。 –