我有Angular 7服务
@Injectable({
providedIn: 'root'
})
export class ClaimsService {
lookupSplitter: KeyValuePair;
constructor(
@Inject(API_CLAIMS_BASE_URL) private apiClaimsBaseUrl: string,
@Inject(LOOKUP_SPLIT_KEY_VALUE) lookupSplitKeyValueConst: KeyValuePair,
private httpClient: HttpClient,
private log: LogService
) {
this.lookupSplitter = lookupSplitKeyValueConst;
}
...
}
我正在尝试创建单元测试:
import { HttpClientModule } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { LogService } from '@app/core/logging/services/log.service';
import { instance, mock } from 'ts-mockito';
import { ClaimsService } from './claims.service';
describe('ClaimsService', () => {
const mockLogService = mock(LogService);
beforeEach(() =>
TestBed.configureTestingModule({
imports: [HttpClientModule, HttpClientTestingModule],
providers: [ClaimsService, { provide: LogService, useFactory: () => instance(mockLogService) }]
})
);
it('should be created', () => {
const service: ClaimsService = TestBed.get(ClaimsService);
expect(service).toBeTruthy();
});
});
哪个给我错误:
Error: StaticInjectorError(DynamicTestModule)[InjectionToken API_CLAIMS_BASE_URL]:
StaticInjectorError(Platform: core)[InjectionToken API_CLAIMS_BASE_URL]:
NullInjectorError: No provider for InjectionToken API_CLAIMS_BASE_URL!
我不确定如何在测试台上进行设置。有人可以帮忙吗?
谢谢。
答案 0 :(得分:0)
一个同事帮我解决了这个问题:
import { HttpClientModule } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { API_CLAIMS_BASE_URL, LOOKUP_SPLIT_KEY_VALUE } from '@app/app-injection-token';
import { LogService } from '@app/core/logging/services/log.service';
import { KeyValuePair } from '@app/core/models/key-value-pair';
import { environment } from '@environments/environment';
import { instance, mock } from 'ts-mockito';
import { ClaimsService } from './claims.service';
describe('ClaimsService', () => {
const mockLogService = mock(LogService);
const lookupSplitKeyValueConst: KeyValuePair = new KeyValuePair('key', 'value');
beforeEach(() =>
TestBed.configureTestingModule({
imports: [HttpClientModule, HttpClientTestingModule],
providers: [
ClaimsService,
{ provide: LogService, useFactory: () => instance(mockLogService) },
{ provide: API_CLAIMS_BASE_URL, useValue: environment.claimsServiceURL },
{ provide: LOOKUP_SPLIT_KEY_VALUE, useValue: lookupSplitKeyValueConst }
]
})
);
it('should be created', () => {
const service: ClaimsService = TestBed.get(ClaimsService);
expect(service).toBeTruthy();
});
});