没有为InjectionToken自定义HTTP配置提供程序

时间:2018-08-23 10:41:50

标签: angular typescript unit-testing karma-jasmine

我对业力和茉莉并不陌生,所以如果听起来很傻,请原谅我。我有以下这些代码,我想使用它来做的事就是找出下一步要做的事情。我在CUSTOM_HTTP_CONFIG的构造函数中注入了hello-http.service.ts,但找不到教程如何实现这一点,手动注入了依赖项,这就是我认为错误消息所抱怨的。

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);
}

因果报应:错误

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)

2 个答案:

答案 0 :(得分: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();
}));
});

答案 1 :(得分:0)

您可以尝试以下操作:-

let svc: HelloHttpService;    

beforeEach(inject([HelloHttpService], (serviceArg: HelloHttpService) => {
    svc = serviceArg;
}));