Angular,测试使用路由器导航时实例化哪个组件 [英] Angular, test which component is instantiate when navigate with router

查看:19
本文介绍了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,测试使用路由器导航时实例化哪个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆