angular2-routing – 如何在angular2中为router.url编写单元测试
发布时间:2020-12-17 18:03:10 所属栏目:安全 来源:网络整理
导读:请帮忙在router.url usging angular上编写单元测试2.请查看下面的代码以了解我的查询. import { Component,OnInit } from '@angular/core';import { Router } from '@angular/router';@Component({ selector: 'app-about',templateUrl: './app-about.compone
请帮忙在router.url usging angular上编写单元测试2.请查看下面的代码以了解我的查询.
import { Component,OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-about',templateUrl: './app-about.component.html',styleUrls: ['./app-about.component.scss'] }) export class AboutComponent implements OnInit { constructor(private router: Router) { if (this.router.url.includes('home')) { ...some functions } } } 解决方法
在我的单元测试中,我不会尝试修改“router.url”,但我导航到想要的网址.
为此,我使用Angular的RouterTestingModule: TestBed.configureTestingModule({ declarations: [MyComponentToTest,DummyComponent],providers: [Location],imports: [RouterTestingModule.withRoutes([{ path: 'search',component: DummyComponent },{ path: 'dashboard',component: DummyComponent }])] }).compileComponents(); 使用Dummy组件: @Component({ template: '' }) class DummyComponent { } 它设置了两个模拟路由的路由器.然后,在测试中我恢复了路由器:const router = TestBed.get(Router);并导航到想要的网址:????router.navigate([ ‘/搜索’]);你可能需要做一个fixture.detectChanges();在任何其他操作之前刷新组件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |