Angular 6测试:如何提供没有嵌套依赖关系的服务?
我有一个Angular 6测试:如何提供没有嵌套依赖关系的服务?,angular,testing,jasmine,karma-runner,injectable,Angular,Testing,Jasmine,Karma Runner,Injectable,我有一个组件a,它使用服务a。我正在为ComponentA编写一个测试,将ServiceA添加到测试床提供者中。我运行测试并得到以下错误: StaticInjectorError(DynamicTestModule)[ServiceA -> ServiceB] NullInjectorError: No provider for ServiceB! 我向提供者添加ServiceB。我再次运行测试,现在我得到: StaticInjectorError(DynamicTestModule)[
组件a
,它使用服务a
。我正在为ComponentA
编写一个测试,将ServiceA
添加到测试床提供者中。我运行测试并得到以下错误:
StaticInjectorError(DynamicTestModule)[ServiceA -> ServiceB]
NullInjectorError: No provider for ServiceB!
我向提供者添加ServiceB
。我再次运行测试,现在我得到:
StaticInjectorError(DynamicTestModule)[ServiceB -> ServiceC]
NullInjectorError: No provider for ServiceC!
我的项目有许多嵌套依赖项,所有服务都有@Injectable
装饰器。如何避免提供嵌套服务的长列表?在.spec.ts文件中:
providers: [
{provide: YourService, useClass: YourMockService},
]
您的MockService将具有与您的服务相同的方法,但通常只是空方法。下面是一个模拟服务:
import { Injectable } from '@angular/core'
@Injectable()
export class YourMockService {
get user() {
// this is mock data
return {username: 'fred'}
}
public getFromLocalStorage(k: string) {
return []
}
}
您的服务将具有这些相同的方法和getter,但将执行HTTP请求等以获取用户名。可能重复的可能重复