angular - 没有 InjectionToken 自定义 HTTP 配置的提供程序

标签 angular typescript unit-testing karma-jasmine

我是 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/

相关文章:

对基于 ANTLR 的树的语义分析访问者进行单元测试

angular - 如何从 Angular 2 中的 url 获取值

angular - 更新 Angular/ngrx reducer 中的嵌套状态结构

Typescript 找不到自定义类型定义文件

javascript - 删除周六和周日,仅获取该月中的几天

python - Django unittest 只读测试数据库

node.js - 如何在 NodeJS 中模拟嵌套依赖关系

angular - 如何从 URL(路由)Angular 2 获取参数?

angular - Angular2 中的 ReactiveFormsModule 与 FormsModule

javascript - 检查设备是否支持 ScreenOrientation.lock() - Uncaught Error screen.orientation.lock() 在此设备上不可用