Angular 服务注入其他服务的角度单元测试
我以前写过角度测试,但是我不知道如何创建一个涵盖以下代码的测试。我将包括我已经连线的内容,但测试是基本的 以下是服务文件:Angular 服务注入其他服务的角度单元测试,angular,unit-testing,angular8,Angular,Unit Testing,Angular8,我以前写过角度测试,但是我不知道如何创建一个涵盖以下代码的测试。我将包括我已经连线的内容,但测试是基本的 以下是服务文件: @Injectable() export class HealthViewService { constructor(private readonly healthService: HealthService, private router: Router){} createNewPatient() { this.healthService.
@Injectable()
export class HealthViewService {
constructor(private readonly healthService: HealthService, private router: Router){}
createNewPatient() {
this.healthService.currentStatus = this.healthService.getInitialStatus();
this.router.navigate('health/patient');
}
}
这是规范文件:
import {HealthViewService} from '<not showing pathway>';
import {HealthService} from '<not showing pathway again>';
const healthViewService = {
createNewPatient: () => {}
}
const healthServiceStub = { currentStatus: () { return StatusTarget.Inbound; }}
let routerStub = { navigate: () => {} }
describe('HealthViewService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: Router, useValue: routerStub },
{provide: HealthService, useValue: healthServiceStub },
{provide: HealthViewService, useValue: healthViewService}]
})
});
describe('createNewPatient', () => {
it('it should route to patient page', () => {
expect(healthViewService.createNewPatient).toBeTruthy();
});
});
});
好消息是这个测试通过了,但它并不是一个真正的代码覆盖率测试。我的问题是:有没有什么方法可以让我正确地模拟路由器,并观察路由器在哪里导航?我可以监视HealthService来检查那里的值吗?任何帮助都将不胜感激。您的代码中有几个问题: spec文件不会测试HealthViewService类的实际实现,因为您提供了某种伪对象const HealthViewService={createNewPatient:=>{}作为该服务的实例 您希望healthViewService.createNewPatient方法存在,如果不调用该方法,则该方法始终为真 router navigate方法需要字符串数组,而不是字符串数组
这是修复程序,你可以考虑我删除了HealthService部分给你一个MWE
@注射的 导出类HealthViewService{ 构造函数私有路由器:路由器{} 创建新患者{ 这个.路由器.导航[健康,病人]; } } 以及相应的规范文件 从@angular/core/testing导入{TestBed}; 从@angular/Router导入{Router}; 从./health-view-service.service导入{HealthViewService}; describeHealthViewServiceService,=>{ beforeach=>{ TestBed.configureTestingModule{ 供应商:[ //提供要测试的实际实现 //{provide:HealthViewService,useClass:HealthViewService}的快捷方式 HealthViewService, //提供模拟路由器,通过angular提供的控制机制反转注入 {提供:路由器,使用值:{导航:=>{}}, ], }; }; itcreateNewPatient应导航至健康/患者,=>{ const service=TestBed.injectHealthViewService; const router=TestBed.injectRouter; const spy=间谍路由器,导航; service.createNewPatient; 期望与[健康,病人]一起生活; }; };包括涵盖许多不同场景的文章。注意:这是针对angular 11的。对于angular 8,您可能需要用TestBed.Get替换TestBed.inject,这正是我要找的!非常感谢。