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

问题描述 投票:1回答:1

我是单元测试的新手,尝试阅读几个课程,如何测试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')
    }
  ));


});
angularjs angular jasmine karma-jasmine router
1个回答
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']);
    });
© www.soinside.com 2019 - 2024. All rights reserved.