2016-12-01 100 views
6

如何在Angular 2中模擬函數的點擊事件?對於我的家庭成分,我有:Angular 2 Jasmine如何測試組件的功能

首頁組件

import { Component } from '@angular/core'; 
import { Router } from '@angular/router'; 

@Component({ 
    moduleId: module.id, 
    templateUrl: 'home.component.html', 
    styleUrls: ['home.component.css'], 
    selector: 'home', 
}) 
export class HomeComponent { 

    constructor(private router: Router) { 

    } 

    redirectToUpload() { 
     this.router.navigate(['/upload']); 
    } 
    redirectToAbout() { 
     this.router.navigate(['/about']); 
    } 

} 

首頁組件規格

import { ComponentFixture, TestBed, async } from '@angular/core/testing'; 
import { HomeComponent } from './home.component'; 
import { DebugElement } from '@angular/core'; 
import { By } from '@angular/platform-browser'; 
import { Router } from '@angular/router'; 
import { HomeModule } from './home.module'; 
import { RouterLinkStubDirective, RouterOutletStubComponent } from '../../../test/router-stubs'; 
import { RouterModule } from '@angular/router'; 


export function main() { 

    let de: DebugElement; 
    let comp: HomeComponent; 
    let fixture: ComponentFixture<HomeComponent>; 
    let mockRouter:any; 
    class MockRouter { 
     //noinspection TypeScriptUnresolvedFunction 
     navigate = jasmine.createSpy('navigate'); 
    } 



    describe('Home component',() => { 

     // preparing module for testing 
     beforeEach(async(() => { 
      mockRouter = new MockRouter(); 
      TestBed.configureTestingModule({ 
       imports: [HomeModule], 

      }).overrideModule(HomeModule, { 
       remove: { 
        imports: [ RouterModule ], 

       }, 
       add: { 
        declarations: [ RouterLinkStubDirective, RouterOutletStubComponent ], 
        providers: [ { provide: Router, useValue: mockRouter }], 
       } 
      }).compileComponents().then(() => { 

       fixture = TestBed.createComponent(HomeComponent); 
       comp = fixture.componentInstance; 


      }); 
     })); 
      tests(); 
     }); 

     function tests() { 


      beforeEach(() => { 
       // trigger initial data binding 
       fixture.detectChanges(); 



       de = fixture.debugElement.query(By.css('h1')); 

      }); 

      it('can instantiate Home',() => { 
       expect(comp).not.toBeNull(); 
      }); 


      it('should have expected <h1> text',() => { 
       fixture.detectChanges(); 
       const h1 = de.nativeElement; 
       expect(h1.innerText).toMatch("Home"); 
      });   


     } 

} 

我想測試redirectToUpload()和redirectToAbout()。我將如何嘲笑點擊並確保重定向用於指定的鏈接?

回答

7

首先,我建議你在寫作打字稿測試,它讓你的組件與測試之間的凝聚力。

以下是你的spec文件的基本步驟:

獲取元素(如果可能的話,我建議使用一個ID標籤)

const element = fixture.debugElement.query(By.css("#your-element")); 

觸發事件。 注:必須有一個(click)事件的元素上

element.triggerEventHandler("click", null); 

然後檢測從事件

fixture.detectChanges(); 

在HTML模板中的變化,你需要有點擊事件指着功能你想測試(click)="redirectToUpload()"

+0

我們可以稱上述步驟等於模擬點擊嗎? – Aditya

6

你需要獲得按鈕,然後單擊它

de.nativeElement.querySelector('.theButtonClass').click(); 

然後檢查存根的navigate方法被調用正確的說法

expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']); 

您可以使用async或可能不需要。如果它不工作,你可能需要使用async並等待異步點擊事件,以穩定

import { async } from '@angular/core/async'; 

it('..', async(() => { 
    ...click(); 
    fixture.whenStable().then(() => { 
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']); 
    }) 
}) 
相關問題