测试单击按钮后是否调用正确的路径

时间:2017-01-13 10:56:54

标签: angularjs angular jasmine karma-jasmine router

我是单位测试的新手,尝试阅读几个课程,如何测试ng2组件,路由器等。但我仍然不知道如何实现这一点。

我想测试"登录"点击#logout按钮后激活路线。

这是我到目前为止所得到的,但是它根本没有工作部分工作。当我拨打spy.calls.first()时,我会undefined,但是当我拨打spy.calls.all()时,我可以看到预期的结果。

import { ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { Router } from '@angular/router';
import { DebugElement }    from '@angular/core';
import { async } from '@angular/core/testing';

import { HomeComponent } from './home.component';

import { click } from '../testing/index'

class RouterStub {
  navigate(url: string) { return url; }
}

describe('HomeComponent', () => {

  let comp:    HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;
  let logoutBtnEl: HTMLElement;

  // async beforeEach
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      declarations: [ HomeComponent ], // declare the test component
      providers: [
        { provide: Router,      useClass: RouterStub }
      ]
    })
    .compileComponents();  // compile template and css
  }));


  // synchronous beforeEach
  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    comp = fixture.componentInstance; // BannerComponent test instance

    de = fixture.debugElement.query(By.css('h1'));  // query for the title <h1> by CSS element selector
    el = de.nativeElement;
    logoutBtnEl = fixture.debugElement.query(By.css('#logout')).nativeElement;
    fixture.detectChanges(); // trigger initial data binding
  });

  it('should display contain \'Welcome\' in title', () => {
    expect(el.textContent).toContain("Welcome");
  });

  it('should tell ROUTER to navigate when logout clicked',
    inject([Router], (router: Router) => {
        const spy = spyOn(router, 'navigate');
        click(logoutBtnEl);
        console.log(spy.calls.first())
        const navArgs = spy.calls.first().args[0];
        expect( navArgs ).toBe('login', 'should nav to login screen')
    }
  ));


});

1 个答案:

答案 0 :(得分:0)

这对我有用:

使用:RouterTestingModule

import { RouterTestingModule } from '@angular/router/testing';

导入:

imports: [
                etc...,
                RouterTestingModule
            ],

然后对其进行测试:

let component: DashboardComponent;

it ('should be able to go to login on click', () => {
        spyOn(component.router, 'navigate').and.returnValue(true);
        component.logout();
        expect(component.router.navigate).toHaveBeenCalledWith(['login']);
    });
相关问题