请帮忙在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:
为此,我使用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();在任何其他操作之前刷新组件.