angular - 如何编写测试用例来调用“路由器导航端订阅”中的方法?
问题描述
我正在根据路由器事件创建一些面包屑。我创建了一个带有 navigationEnd 和模拟路由器的路由器测试台,但无法正常工作。不明白如何在订阅中调用我的方法以及如何为此编写测试用例来调用这些方法
ngOnInit() {
this.router.events.pipe(filter(e instance of NavigationEnd)).subscribe( event => {
// calling this method
this.callmethod();
// Initiating my breadcrumb method by passing the event
this.initiateBreadcrumb(event);
});
解决方案
你可以这样做:
it('routing should call callmethod', () => {
let callMethodSpy = spyOn(component, "callmethod").and.callThrough();
component.ngOnInit();
let event = new NavigationEnd(42, '/some-route', '/');
TestBed.get(Router).events.next(event);
expect(callMethodSpy).toHaveBeenCalled();
});
并且不要忘记导入RouterTestingModule
到您的TestBed
.
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
...
]
});
推荐阅读
- javascript - Highcharts:如果先前的数组只有空值,则系列不会更新
- mysql - 错误代码:1290。MySQL 服务器正在使用 --secure-file-priv 选项运行
- list - Flutter 应用中的无限列表
- xpages - 如何从 XPage 的 radiogroup 中的 sessionscope 中获取价值
- php - 使用 .htaccess/functions.php 更改搜索网址
- javascript - 由于不推荐使用的圆形 json,Angular 项目创建失败
- c# - 如何设置 WCF IIS 托管服务自动启动?
- computer-vision - Pytorch:修改 VGG16 架构
- python - Python Pandas 连接多个数据帧
- swift - 十进制字段的正则表达式问题 - Swift