angular - 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();
}));
});
解决方案
推荐阅读
- javascript - 如何使用 mongoDB 中的值数组更新文档数组?
- html - 如何水平居中弹性盒并删除剩余空间?
- c# - C# - 从 Oracle DB 生成 POCO
- java - 具有用于 XSD 验证的线程安全缓存
- java - 数学表达式中的字符串匹配 x <= 900 (int, int)
- flutter - 无法构建用于发布的颤振 apk
- python - 构建预测 Pandas DataFrame
- h2o - H2O 目标编码器 Mojo 模型抛出 NULL 指针异常
- python - 在 Maya 中使用 Python 沿 nurbsPlane 创建毛囊以获得丝带 Spine?
- tensorflow - 如何使用 tensorFlow 2 Object Detection API 绘制ground truth bbox?