如何用角度编写单元测试以测试订阅块中的路由代码

时间:2020-07-13 18:50:14

标签: angular typescript unit-testing jasmine karma-jasmine

我是茉莉花和业力中进行角度单元测试的新手,这里我正在尝试测试路由器导航,这里我们有一个向其发送一些数据的服务,并且在我正在导航到链接的订阅块中,< / 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'属性

1 个答案:

答案 0 :(得分:1)

创建2个模拟:

  1. 服务:
export class MockFormservice{
   formMethod(){
     return of({})
   }
}

  1. 对于路由器:
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的基础知识。让我知道是否需要更多帮助