[英]Angular: How to write a unit test for template variable
單擊按鈕時,我正在工作頁面自動滾動,並且我使用模板變量作為目標點。 如何為以模板 var 作為參數的scrollToSecondPage
function 編寫單元測試。
app.component.html
<section>
<p>section 1</p>
<button (click)="scrollToSecondPage(slide2)">Go to section 2</button>
</section>
<section #slide2>
<p>section 2</p>
</section>
app.component.ts
scrollToSecondPage(el: any): void {
el.scrollIntoView({ behavior: 'smooth' });
}
app.component.spec.ts
it('should scroll down to section two', () => {
let component = fixture.componentInstance;
let spy = spyOn(component, 'scrollToSecondPage').and.callThrough();
expect(spy).toHaveBeenCalled();
});
如果您只想進行單元測試,這應該可以解決問題。
import createSpy = jasmine.createSpy;
it('should scroll down to section two', () => {
let component = fixture.componentInstance;
const scrollSpy = createSpy('scrollIntoView')
const el = {
scrollIntoView: scrollSpy,
}
component.scrollToSecondPage(el);
expect(scrollSpy).toHaveBeenCalledWith({ behavior: 'smooth' });
});
您將創建一個可以檢查調用的間諜,然后將其傳遞給方法並檢查該間諜是否已被組件調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.