问题描述
我正在为 angular 应用程序运行单元测试,我想对导航在 angular 应用程序中是否正常工作进行单元测试.
if (this.customer.length == 0) {this.router.navigate(['/nocustomer']);}
和单元测试
it(`应该导航到 nocustomer`,()=>{component.customers.length=0;//这里必须写什么来检查这个})
在 Angular 中检查 单元测试路由器
执行以下操作
1) 从@angular 导入路由器.
import { Router } from '@angular/router';
2) 将路由器添加到您的 providers 数组并将其替换为 routerSpy.
TestBed.configureTestingModule({供应商: [{ 提供:路由器,使用值:routerSpy }]})
3)最后,创建routerSpy并创建一个jasmine spy来观察导航方法.
let routerSpy = {navigate: jasmine.createSpy('navigate')};
如果组件在测试运行时找不到 <router-outlet></router-outlet>
元素,这将阻止您的单元测试失败.
然后您可以使用以下命令测试 router.navigate() 是否已被调用:
expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
因此,修改您的 it()
语句,如下所示并添加以上内容配置
it(`应该导航到 nocustomer`, () => {component.customers = [];期望 (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);});
I am running unit test for angular app, I want to unit test if navigation is working correctly in angular app.
if (this.customer.length == 0) {
this.router.navigate(['/nocustomer']);
}
And the unit test for this
it(`should navigate to nocustomer`,()=>{
component.customers.length=0;
//what must be written here to check this
})
Check unit testing router in Angular
Do the following
1) Import the Router from @angular.
import { Router } from '@angular/router';
2) Add the Router to your providers array and swap it out for a routerSpy.
TestBed.configureTestingModule({
providers: [
{ provide: Router, useValue: routerSpy }
]
})
3) Finally, create routerSpy and create a jasmine spy to watch the navigate method.
let routerSpy = {navigate: jasmine.createSpy('navigate')};
This will stop your unit test failing when the component can’t find the <router-outlet></router-outlet>
element when the test runs.
You can then test that router.navigate() has been called using:
expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
it(`should navigate to nocustomer`, () => {
component.customers = [];
expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
});
这篇关于如何在 angular 应用程序中对 router.navigate 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!