如何在 angular 2 中测试“Router NavigationEnd Event”?

Mar*_* M. 7 unit-testing jasmine angular-routing angular

有谁知道我该如何测试Router NavigationEnd Event?我在 Angular 2 中有下面的代码,我正在使用 Jasmine。

import { Injectable, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, Event } from '@angular/router';

@Injectable()
export class IhmPageClassService {
    emitPageClass = new EventEmitter<string>();
    currentRoute: string;

    constructor(router: Router) {
        router.events.subscribe((event: Event) => {
            if (event instanceof NavigationEnd) {
                this.currentRoute = (<NavigationEnd>event).url;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

Fel*_*sai 5

所以我很幸运地使用 Subjects 测试了这个。

在您的测试设置中,您创建了一个 eventsSubject。

let eventsSub = new BehaviorSubject<any>(null);

然后创建您的 routerStub:

routerStub = { events: eventsSub }

然后创建 NavigationEnd 对象。

let homeNav = new NavigationEnd(1, 'home', 'home');
Run Code Online (Sandbox Code Playgroud)

现在Router在您的测试中使用 routerStub 作为Service的值,您现在应该能够测试您的功能。

it('should set the currentRoute correctly', () => {
  eventSub.next(homeNav);
  fixture.detectChanges();
  expect(component.currentRoute).toEqual('home')      
});
Run Code Online (Sandbox Code Playgroud)


Yak*_*ain -3

我不确定为什么您需要测试路由器事件,但如果您想调试它们,请启用跟踪选项,如下所示:

RouterModule.forRoot(routes, { enableTracing: true })
Run Code Online (Sandbox Code Playgroud)

这将在浏览器控制台上打印有关路由器事件的信息: 在此输入图像描述

  • 因为我得到 Router Event 后有更多代码,我需要测试它。我的意思是,我需要代码覆盖率。 (5认同)