2017-06-27 46 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對象,可以這樣使用。 在你的情況下,你確實有一個窺探的功能。 –