Angular 2 Jasmine如何测试组件的功能

时间:2016-12-01 16:22:57

标签: angular jasmine karma-jasmine angular2-routing

如何在Angular 2中模拟函数的click事件?对于我的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']);
    }

}

主页组件规范

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()。我如何模拟点击并确保重定向是指定链接?

2 个答案:

答案 0 :(得分:7)

首先,我建议您在Typescript中编写测试,它会保持组件与测试之间的内聚。

以下是规范文件中的基本步骤:

获取元素(如果可能,我建议使用Id标记)

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

触发事件。 注意:元素上必须有(click)个事件

element.triggerEventHandler("click", null);

然后检测事件的变化

fixture.detectChanges();

在HTML模板中,您需要指向要测试的功能的点击事件(click)="redirectToUpload()"

答案 1 :(得分: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']);
  })
})