Angular 2 Jasmine How to test a function of a comp

2019-02-17 10:10发布

How do I mock the click event of a function in Angular 2? For my Home Component I have:

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

}

Home Component spec

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


        }

}

I want to test redirectToUpload() and redirectToAbout(). How would I mock the click and ensure that the redirect is for the specified link?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-17 10:37

First, I recommend you writing your test in Typescript, it keeps cohesion between your components and your tests.

Here are the basic steps in your spec file:

Get the element (I recommend using an Id tag if possible)

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

Trigger the event. NOTE: there must be a (click) event on the element

element.triggerEventHandler("click", null);

Then detect the changes from the event

fixture.detectChanges();

In your HTML template, you would need to have click events pointed at the functions you wish to test (click)="redirectToUpload()"

查看更多
女痞
3楼-- · 2019-02-17 10:49

You need to get the button then click it

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

Then check that the stub's navigate method is called with the correct argument

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

You may or may not need to use async. If it doesn't work, you might need to use async and wait for the asynchronous click event to stabilize

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

it('..', async(() => {
  ...click();
  fixture.whenStable().then(() => {
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']);
  })
})
查看更多
登录 后发表回答