2016-12-01 21 views
6

Làm cách nào để giả lập sự kiện nhấp của một hàm trong Angular 2? Đối với Hợp phần Trang chủ của tôi, tôi có:Góc 2 Jasmine Làm thế nào để kiểm tra chức năng của một thành phần

Home Component

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']); 
    } 

} 

Trang chủ Hợp phần đặc tả

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"); 
      });   


     } 

} 

Tôi muốn thử nghiệm redirectToUpload() và redirectToAbout(). Làm thế nào tôi sẽ giả lập nhấp chuột và đảm bảo rằng chuyển hướng là dành cho liên kết được chỉ định?

Trả lời

7

Trước tiên, tôi khuyên bạn nên viết thử nghiệm của bạn trong nguyên cảo, nó giữ sự gắn kết giữa các thành phần của bạn và kiểm tra của bạn.

Dưới đây là các bước cơ bản trong tập tin spec của bạn:

Lấy phần tử (tôi khuyên bạn nên sử dụng một thẻ Id nếu có thể)

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

Kích hoạt sự kiện này. LƯU Ý: phải có một sự kiện (click) trên phần tử

element.triggerEventHandler("click", null); 

Sau đó, phát hiện những thay đổi từ sự kiện

fixture.detectChanges(); 

Trong mẫu HTML của bạn, bạn sẽ cần phải có sự kiện nhấp chuột chỉ vào các chức năng bạn muốn thử nghiệm (click)="redirectToUpload()"

+0

Chúng tôi có thể gọi các bước trên bằng cách mô phỏng nhấp chuột không? – Aditya

6

Bạn cần phải nhận được nút sau đó nhấp vào nó

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

Sau đó kiểm tra rằng phương pháp của cuống navigate được gọi với đối số đúng

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

Bạn có thể hoặc không cần phải sử dụng async. Nếu nó không hoạt động, bạn có thể cần phải sử dụng async và chờ cho sự kiện nhấp chuột không đồng bộ để ổn định

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

it('..', async(() => { 
    ...click(); 
    fixture.whenStable().then(() => { 
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']); 
    }) 
}) 
Các vấn đề liên quan