请帮忙在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
在我的单元测试中,我不会尝试修改“router.url”,而是导航到所需的 url。
为此,我使用 Angular 的 RouterTestingModule:
TestBed.configureTestingModule({
declarations: [MyComponentToTest, DummyComponent],
providers: [Location],
imports: [RouterTestingModule.withRoutes([{ path: 'search', component: DummyComponent },
{ path: 'dashboard', component: DummyComponent }])]
}).compileComponents();
Run Code Online (Sandbox Code Playgroud)
使用虚拟组件:
@Component({ template: '' })
class DummyComponent { }
Run Code Online (Sandbox Code Playgroud)
它使用两条模拟路由设置路由器。
然后,在测试中我恢复路由器:
const router = TestBed.get(Router);
并导航到所需的 url:
router.navigate(['/search']);
您可能需要在执行fixture.detectChanges();任何其他操作之前刷新组件。
| 归档时间: |
|
| 查看次数: |
490 次 |
| 最近记录: |