kar*_*nal 8 router unit-testing navigateurl angular
我正在为 angular 应用程序运行单元测试,我想对导航在 angular 应用程序中是否正常工作进行单元测试。
if (this.customer.length == 0) {
this.router.navigate(['/nocustomer']);
}
Run Code Online (Sandbox Code Playgroud)
以及为此的单元测试
it(`should navigate to nocustomer`,()=>{
component.customers.length=0;
//what must be written here to check this
})
Run Code Online (Sandbox Code Playgroud)
Sou*_*tta 23
请执行下列操作
1) 从@angular 导入路由器。
import { Router } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)
2) 将路由器添加到您的 providers 阵列并将其替换为 routerSpy。
TestBed.configureTestingModule({
providers: [
{ provide: Router, useValue: routerSpy }
]
})
Run Code Online (Sandbox Code Playgroud)
3)最后创建routerSpy,并创建一个jasmine spy来观看navigate方法。
let routerSpy = {navigate: jasmine.createSpy('navigate')};
Run Code Online (Sandbox Code Playgroud)
当组件<router-outlet></router-outlet>
在测试运行时找不到元素时,这将阻止您的单元测试失败。
然后,您可以使用以下命令测试 router.navigate() 是否已被调用:
expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
Run Code Online (Sandbox Code Playgroud)
因此,
it()
像下面这样修改你的语句并添加上面的配置
it(`should navigate to nocustomer`, () => {
component.customers = [];
expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
});
Run Code Online (Sandbox Code Playgroud)
有时,我动态地放置其他参数来调用导航。因此,只期望我在测试中使用的路径:
...
test('Navigate to /nextPage.', inject([Router], (mockRouter: Router) => {
const spy = spyOn(mockRouter, 'navigate').and.stub();
component.goToNextPageMethod();
expect(spy.calls.first().args[0]).toContain('/nextPage');
}));
...
Run Code Online (Sandbox Code Playgroud)
参考:https://semaphoreci.com/community/tutorials/testing-routes-in-angular-2
归档时间: |
|
查看次数: |
18646 次 |
最近记录: |