[英]Angular 6 - how to mock router.events url response in unit test
As the title indicates, I need to mock router.events
in a unit test.正如标题所示,我需要在单元测试中模拟router.events
。
In my component, I doing some regex to grab the first instance of text between slashes in the url;在我的组件中,我做了一些正则表达式来获取 url 中斜杠之间的第一个文本实例; eg, /pdp/
例如, /pdp/
constructor(
private route: ActivatedRoute,
private router: Router,
}
this.router.events.pipe(takeUntil(this.ngUnsubscribe$))
.subscribe(route => {
if (route instanceof NavigationEnd) {
// debugger
this.projectType = route.url.match(/[a-z-]+/)[0];
}
});
My unit tests error out when the component is being built: Cannot read property '0' of null
.我的单元测试在构建组件时出错: Cannot read property '0' of null
。 When I comment-in the debugger, route
does not seem to be set correctly, yet I am setting it in the unit test itself.当我在调试器中注释时, route
似乎没有正确设置,但我在单元测试本身中设置了它。 I have done it several different ways (inspired by this post: Mocking router.events.subscribe() Angular2 and others).我已经完成了几种不同的方式(受这篇文章的启发: Mocking router.events.subscribe() Angular2和其他)。
First attempt:第一次尝试:
providers: [
{
provide: Router,
useValue: {
events: of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit'))
}
},
// ActivatedRoute also being mocked
{
provide: ActivatedRoute,
useValue: {
snapshot: { url: [{ path: 'new' }, { path: 'edit' }] },
parent: {
parent: {
snapshot: {
url: [
{ path: 'pdp' }
]
}
}
}
}
}
]
Second attempt (based on the above post):第二次尝试(基于上述帖子):
class MockRouter {
public events = of(new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit'))
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
Third attempt (also based on above post):第三次尝试(也基于上述帖子):
class MockRouter {
public ne = new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit');
public events = new Observable(observer => {
observer.next(this.ne);
observer.complete();
});
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
Fourth attempt:第四次尝试:
beforeEach(() => {
spyOn((<any>component).router, 'events').and.returnValue(of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit')))
...
Fifth attempt:第五次尝试:
beforeEach(() => {
spyOn(TestBed.get(Router), 'events').and.returnValue(of({ url:'/pdp/project-details/4/edit' }))
...
In all the above cases, route
is not being set;在上述所有情况下,都没有设置route
; the NavigationEnd
object is equal to: NavigationEnd
对象等于:
{ id: 1, url: "/", urlAfterRedirects: "/" }
Thoughts?想法?
It can be as simple as:它可以很简单:
TestBed.configureTestingModule({
imports: [RouterTestingModule]
}).compileComponents()
...
const event = new NavigationEnd(42, '/', '/');
(TestBed.inject(Router).events as Subject<Event>).next(event);
Here is the answer I came up with.这是我想出的答案。 I think I just didn't extend the first approach (above) far enough:我想我只是没有将第一种方法(以上)扩展得足够远:
import { of } from 'rxjs';
import { NavigationEnd, Router } from '@angular/router';
providers: [
{
provide: Router,
useValue: {
url: '/non-pdp/phases/8',
events: of(new NavigationEnd(0, 'http://localhost:4200/#/non-pdp/phases/8', 'http://localhost:4200/#/non-pdp/phases/8')),
navigate: jasmine.createSpy('navigate')
}
}
]
Thought this might help...have a footer component with routerLinks in the template.认为这可能会有所帮助...在模板中有一个带有 routerLinks 的页脚组件。 Was getting the root not provided error....had to use a "real" router...but have a spied variable..and point the router.events to my test observable so I can control nav events正在获取根未提供错误....必须使用“真实”路由器...但有一个间谍变量..并将 router.events 指向我的测试可观察对象,以便我可以控制导航事件
export type Spied<T> = { [Method in keyof T]: jasmine.Spy };
describe("FooterComponent", () => {
let component: FooterComponent;
let fixture: ComponentFixture<FooterComponent>;
let de: DebugElement;
const routerEvent$ = new BehaviorSubject<RouterEvent>(null);
let router: Spied<Router>;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [provideMock(SomeService), provideMock(SomeOtherService)],
declarations: [FooterComponent],
imports: [RouterTestingModule]
}).compileComponents();
router = TestBed.get(Router);
(<any>router).events = routerEvent$.asObservable();
fixture = TestBed.createComponent(FooterComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
}));
// component subscribes to router nav event...checking url to hide/show a link
it("should return false for showSomeLink()", () => {
routerEvent$.next(new NavigationEnd(1, "/someroute", "/"));
component.ngOnInit();
expect(component.showSomeLink()).toBeFalsy();
fixture.detectChanges();
const htmlComponent = de.query(By.css("#someLinkId"));
expect(htmlComponent).toBeNull();
});
I saw this alternative and it works with RouterTestingModule
like @daniel-sc 's answer我看到了这个替代方案,它与RouterTestingModule
工作,就像 @daniel-sc 的答案
const events = new Subject<{}>();
const router = TestBed.get(Router);
spyOn(router.events, 'pipe').and.returnValue(events);
events.next('Result of pipe');
Hope this could help, this is what I did:希望这会有所帮助,这就是我所做的:
const eventsStub = new BehaviorSubject<Event>(null);
export class RouterStub {
events = eventsStub;
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [RouterTestingModule],
providers: [
{ provide: HttpClient, useValue: {} },
{ provide: Router, useClass: RouterStub },
Store,
CybermetrieCentralizedService,
TileMenuComponentService,
HttpErrorService
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
router = TestBed.get(Router);
tileMenuService = TestBed.get(TileMenuComponentService);
component = fixture.componentInstance;
}));
and then on the test I did this:然后在测试中我这样做了:
it('should close the menu when navigation to dashboard ends', async(() => {
spyOn(tileMenuService.menuOpened, 'next');
component.checkRouterEvents();
router.events.next(new NavigationEnd (1, '/', '/'));
expect(tileMenuService.menuOpened.next).toHaveBeenCalledWith(false);
}));
this to verify that after the navigation to route '/' I execute an expected instruction这是为了验证在导航到路由“/”之后我执行了预期的指令
ReplaySubject<RouterEvent>
to mock the router.events
使用ReplaySubject<RouterEvent>
来模拟router.events
filter
instead of instanceof
使用filter
代替instanceof
import {Injectable} from '@angular/core';
import {NavigationEnd, Router, RouterEvent} from '@angular/router';
import {filter, map} from 'rxjs/operators';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RouteEventService {
constructor(private router: Router) {
}
subscribeToRouterEventUrl(): Observable<string> {
return this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map((event: RouterEvent) => event.url)
);
}
}
import {TestBed} from '@angular/core/testing';
import {RouteEventService} from './route-event.service';
import {NavigationEnd, NavigationStart, Router, RouterEvent} from '@angular/router';
import {Observable, ReplaySubject} from 'rxjs';
describe('RouteEventService', () => {
let service: RouteEventService;
let routerEventRelaySubject: ReplaySubject<RouterEvent>;
let routerMock;
beforeEach(() => {
routerEventRelaySubject = new ReplaySubject<RouterEvent>(1);
routerMock = {
events: routerEventRelaySubject.asObservable()
};
TestBed.configureTestingModule({
providers: [
{provide: Router, useValue: routerMock}
]
});
service = TestBed.inject(RouteEventService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('subscribeToEventUrl should', () => {
it('return route equals to mock url on firing NavigationEnd', () => {
const result: Observable<string> = service.subscribeToRouterEventUrl();
const url = '/mock';
result.subscribe((route: string) => {
expect(route).toEqual(url);
});
routerEventRelaySubject.next(new NavigationEnd(1, url, 'redirectUrl'));
});
it('return route equals to mock url on firing NavigationStart', () => {
const result: Observable<string> = service.subscribeToRouterEventUrl();
const url = '/mock';
result.subscribe((route: string) => {
expect(route).toBeNull();
});
routerEventRelaySubject.next(new NavigationStart(1, url, 'imperative', null));
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.