我是 karma 和 Jasmine 的新手,所以如果这听起来很愚蠢,请原谅我。我有以下代码,我想用它做的就是找出下一步需要做什么。我在 hello-http.service.ts
的构造函数中注入(inject)了 CUSTOM_HTTP_CONFIG
,我找不到教程如何实现这一点,手动注入(inject)依赖项,这就是我的认为错误消息是在提示。
test.spec.ts
beforeEach(async(() => {
TestBed.configureTestingModule({
declaration: [...],
imports[RouterTestingModule, ...],
providers: [HelloHttpService, ...],
});
});
hello-http.service.ts
constructor(
@Inject(CUSTOM_HTTP_CONFIG) protect config: CustomHttpParams,
...
) {
super(config, http);
}
karma :错误
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();
}));
});
关于angular - 没有 InjectionToken 自定义 HTTP 配置的提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51983927/