我最近将我的应用程序从Angular8迁移到Angular 9。对于所有注入的服务,将Testbed.get(service(更改为Testbed.inject(service(运行良好。
然而,如果服务使用像Testbed.get('StringToken')
这样的String-injectionToken,我会收到很多错误。
原始设置:
//appModule.ts
providers: [
{
provide: 'ApiService',
useClass: ApiService
},
//api.service.ts
@Injectable()
export class ApiService implements ApiServiceInterface {
private baseUrl: string;
constructor(
private http: HttpClient,
private appConfigService: AppConfigService,
) {
this.baseUrl = this.appConfigService.baseUrl();
}
我正在注入APIsevice 的另一项服务
//xyz.service.ts
export class XYZService {
constructor(
@Inject('ApiService') private apiService: ApiServiceInterface,
private configurationService: ConfigurationService,
) {
}
当我在规范文件中使用testbed.get时,一切都很好,但我收到一个警告,testbed.get已贬值。
//xyz.service.spec.ts
describe('XYZService', () => {
let configurationService: ConfigurationService;
let apiService: ApiServiceInterface;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
TranslateModule.forRoot(),
AppTestingModule
],
});
configurationService = TestBed.inject(ConfigurationService);
cacheService = TestBed.inject(CacheService);
apiService = Testbed.get('ApiService');
});
根据angular文档,我在一个单独的文件中创建了一个InjectionToken,并将其导入到各处。这是新设置的
//token.ts
import { InjectionToken } from '@angular/core';
import { ApiService } from './app/services/api/api.service';
export const TOKEN1 = new InjectionToken<ApiService>('ApiService');
//appModule.ts
providers: [
{
provide: TOKEN1,
useClass: ApiService
},
//xyz.service.ts
export class XYZService {
constructor(
@Inject(TOKEN1) private apiService: ApiServiceInterface,
private configurationService: ConfigurationService,
) {
}
//xyz.service.spec.ts
describe('XYZService', () => {
let configurationService: ConfigurationService;
let apiService: ApiServiceInterface;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
TranslateModule.forRoot(),
AppTestingModule
],
});
configurationService = TestBed.inject(ConfigurationService);
cacheService = TestBed.inject(CacheService);
apiService = Testbed.inject(TOKEN1); //Throws a lot of errors
});
似乎服务没有启动,并且没有任何测试正在运行。我是不是遗漏了什么?
在您的tesbed中,添加以下任一提供商
providers: [
{ provide: SomeToken, useValue: someMockObjectHere },
{ provide: 'someString', useValue: anotherMockObject },
]
然后使用注入
apiService = Testbed.inject<any>(SomeToken);
apiService = Testbed.inject<any>('someString');