我是业力和茉莉的新手,所以请原谅我,如果这听起来很傻。我有以下代码以及我想用它做什么,就是找出我接下来要做的事情。我在CUSTOM_HTTP_CONFIG
的构造函数中注入了hello-http.service.ts
,我找不到教程如何实现这一点,手动注入依赖项,这就是我认为错误消息正在抱怨的内容。
test.spec.ts
beforeEach(async(() => {
TestBed.configureTestingModule({
declaration: [...],
imports[RouterTestingModule, ...],
providers: [HelloHttpService, ...],
});
});
你好,http.service.ts
constructor(
@Inject(CUSTOM_HTTP_CONFIG) protect config: CustomHttpParams,
...
) {
super(config, http);
}
业力:错误
Failed: Uncaught (in promise): Error: StaticInjectorError(DynamicTestModule)[HelloHttpService -> InjectionToken Custom HTTP Config]:
StaticInjectorError(Platform: core)[HelloHttpService -> InjectionToken Custom HTTP Config]:
NullInjectorError: No provider for InjectionToken Custom HTTP Config!
Error: StaticInjectorError(DynamicTestModule)[HelloHttpService -> InjectionToken Custom HTTP Config]:
StaticInjectorError(Platform: core)[HelloHttpService -> InjectionToken Custom HTTP Config]:
NullInjectorError: No provider for InjectionToken Custom HTTP Config!
at _NullInjector.webpackJsonp../node_modules/@angular/core/esm5/core.js._NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:1003:1)
at resolveToken (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:1301:1)
尝试这样的事情:
import { TestBed, inject } from '@angular/core/testing';
import { HelloHttpService } from './http.service';
describe('HttpService', () => {
let service : HelloHttpService;
// mock the service, there we no need to pull in any dependency or need to declare constant for the injector aka CUSTOM_HTTP_CONFIG
const mockHelloHttpService() = { } as HelloHttpService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: HelloHttpService,
useValue: mockHelloHttpService, // must do this, or it will try to find the injector token in the custom http service
// which the reason why this error occurred.
}],
});
});
it('should be created', inject([HelloHttpService], (service: HelloHttpService) => {
expect(service).toBeTruthy();
}));
});
您可以尝试以下方法: -
let svc: HelloHttpService;
beforeEach(inject([HelloHttpService], (serviceArg: HelloHttpService) => {
svc = serviceArg;
}));