我运行ng test
命令时显示的错误。
这是我的服务规范,
describe('BackendService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: Http, useFactory: (backend, options) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions,
BackendService
]
});
});
it('should ...', inject([BackendService, MockBackend], (service: BackendService) => {
expect(service).toBeTruthy();
})
); });
BackendService.ts
看起来像,
export class BackendService {
private baseUrl: string = 'https://foo-backend.appspot.com/_ah/api/default/v1';
constructor(private http: Http, baseName: string) {
this.baseUrl = this.baseUrl + baseName;
}
.....
}
似乎BackendService
类的构造函数中的额外参数会导致此问题..
答案 0 :(得分:1)
你如何期望Angular知道baseName
应该是什么?所有构造函数参数都需要从Injector获取。如果参数没有相应的标记,则无法查找它。
您可以通过执行
添加令牌// somewhere in some file
import { OpaqueToken } from '@angular/core';
export const BASE_NAME_TOKEN = new OpaqueToken("app.base_name");
// in test class
import { BASE_NAME_TOKEN } from 'where-ever'
TestBed.configureTestingModule({
providers: [
BackendService,
{ provide: BASE_NAME_TOKEN, useValue: 'whatever-the-base-is' }
]
});
// in service constructor
import { Inject } from '@angular/core'
import { BASE_NAME_TOKEN } from 'where-ever'
constructor(http: Http, @Inject(BASE_NAME_TOKEN) baseName: string) {}
另见: