我是茉莉花和业力中进行角度单元测试的新手,这里我正在尝试测试路由器导航,这里我们有一个向其发送一些数据的服务,并且在我正在导航到链接的订阅块中,< / p>
为此,我该如何编写单元测试。
TS文件中功能的代码。
onAction(action) {
if (action == true) {
this.data.action = action;
this.data.loggedInId = this.id;
this.Formservice.formMethod(this.data).subscribe(() => {
this.router.navigate([`/${this.breadCrum}`]);
});
}
}
SPEC.TS文件的代码
it("Check the router navigate after onAction",fakeAsync(()=> {
component.onAction(true)
flushMicrotasks()
tick(10)
fixture.detectChanges()
tick(10)
expect (mockRouter.navigate).toHaveBeenCalledWith ('/action-taken');
}));
我创建了Mock Router服务的步骤
import { Routes, RouterModule, ActivatedRoute, Router } from '@angular/router';
let mockRouter = {
navigate: jasmine.createSpy('navigate')
}
providers:[
{ provide: Router, useValue: mockRouter}
]
这是我得到的错误无法读取未定义的'subscribe'属性
答案 0 :(得分:1)
创建2个模拟:
export class MockFormservice{
formMethod(){
return of({})
}
}
export class MockRouter{
navigate(){}
}
通过这种方式,您可以在其他组件中再使用它,然后在spec
文件中重复使用它:
providers:[
{ provide: Formservice, useClass: MockFormservice},
{ provide: Router, useClass: MockRouter}
]
您也可以jasmine.createSpy
来使路由器模拟代码简短。您的选择。
我强烈建议您阅读我的article on how to handle such cases。它虽小,但专注于开发人员的日常使用测试。在测试角度代码时,有一系列articles which has covered few more scenarios which will surely help you get comfortable的基础知识。让我知道是否需要更多帮助