本文介绍了Angular,测试使用路由器导航时实例化哪个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有办法在导航到路由时测试哪个组件被实例化.
I'd like to know if there is a way to test which component is instantiate when navigating to a route.
我有这条路线:
const routes: Routes = [{path: ':anyString', component: AnyStringComponent}];
我想用单元测试进行测试:
I want to test with unit-test :
router.navigate(['azdfz4896']);
// expect instantiated component to be AnyStringComponent
有没有办法测试一下?
推荐答案
你可以模拟 ActivatedRoute 并尝试:
you can mock ActivatedRoute and try :
route.snapshot._routeConfig.component.name
从快照
ActivatedRoute 模拟:
ActivatedRoute mock:
export class MockActivatedRoute implements ActivatedRoute{
component : Type<any>|string;
snapshot : ActivatedRouteSnapshot;
url : Observable<UrlSegment[]>;
params : Observable<Params>;
queryParams : Observable<Params>;
data : Observable<Data>;
outlet : string;
...
}
...
你的测试
router = TestBed.get(Router);
location = TestBed.get(Location);
router.initialNavigation();
....
it('navigate to "search" takes you to /search', fakeAsync(() => {
route = new MockActivatedRoute();
router.navigate(['azdfz4896']);
tick();
expect(location.path()).toBe('/azdfz4896');
expect(route.snapshot.component.name).toBe('AnyStringComponent');
}));
希望能帮到你
这篇关于Angular,测试使用路由器导航时实例化哪个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!