首页 > 解决方案 > Angular 6/ Karma:运行 ng 测试时出错

问题描述

运行后出现以下错误ng test,在终端和浏览器中,一切都编译并运行良好。仅在运行测试时。

错误:StaticInjectorError(DynamicTestModule)[ApiService -> InjectionToken END_POINTS]: StaticInjectorError(Platform: core)[ApiService -> InjectionToken END_POINTS]: NullInjectorError: No provider for InjectionToken END_POINTS!

ApiService

import {
  Inject,
  Injectable,
  InjectionToken
} from '@angular/core';
import {
  environment
} from '@env/environment';

export const END_POINTS = new InjectionToken('END_POINTS');

@Injectable()
export class ApiService {
  private readonly _baseUrl = environment.backend;
  endPoints: EndPoints;

  constructor(@Inject(END_POINTS) private _endPoints) {
    this.endPoints = _endPoints.reduce((acc, current) => {
      return {
        ...current,
        ...acc
      };
    }, {});
  }

  resolve(url: string, params ? ) {
    if (!params) {
      return `${this._baseUrl}${url}`;
    }
    const resolved = Object.keys(params).reduce((acc, param) => {
      return acc.replace(`:${param}`, params[param]);
    }, url);
    return `${this._baseUrl}${resolved}`;
  }

}

认证服务

import {
  Injectable
} from '@angular/core';
import {
  HttpClient
} from '@angular/common/http';

import {
  ApiService
} from '../core/api.service';


@Injectable()
export class AuthService {

  constructor(
    private _api: ApiService,
    private http: HttpClient
  ) {}

  private getOAuthToken(): void {
    const url = this._api.resolve(this._api.endPoints.login);
    this.http.get(url);
  }

}

AuthService.spec,失败的测试之一。

import {
  ApiService
} from './../core/api.service';
import {
  TestBed,
  inject
} from '@angular/core/testing';

import {
  AuthService
} from './auth.service';

describe('AuthService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthService, ApiService]
    });
  });

  it('should be created', inject([AuthService], (service: AuthService) => {
    expect(service).toBeTruthy();
  }));
});

标签: angularjasminekarma-jasmine

解决方案


推荐阅读