[英]How to test component with a @Inject text in the constructor in Angular
[英]How to prepare a test for an Angular 7 Service that using @Inject() in the constructor
我有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!
我不確定如何在測試平台上進行設置。 有人可以幫忙嗎?
提前致謝。
一位同事幫助我解決了這個問題:
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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.