我在运行ng test
后收到以下错误,在终端和浏览器中,所有内容都编译并运行正常。只有在运行测试时才会这样做。
错误:StaticInjectorError(DynamicTestModule)[ApiService - > InjectionToken END_POINTS]: StaticInjectorError(平台:核心)[ApiService - > InjectionToken END_POINTS]: NullInjectorError:没有PullToken的提供者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();
}));
});