[英]Angular 7 Dependency Inject HttpClient into Typescript export function
[英]How to correctly inject HttpClient into a dependency?
我開始學習測試 Angular 服務。 Angular 測試指南中有官方示例。 但在示例中,一個服務依賴於另一個服務的更簡單版本。
/// HeroService method tests begin ///
describe('#getHeroes', () => {
let expectedHeroes: Hero[];
beforeEach(() => {
heroService = TestBed.inject(HeroService);
expectedHeroes = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
] as Hero[];
});
it('should return expected heroes (called once)', () => {
heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
fail
);
const req = httpTestingController.expectOne(heroService.heroesUrl);
expect(req.request.method).toEqual('GET');
req.flush(expectedHeroes);
});
我有一個 TerritoryApiService ,其中包含一組用於處理區域列表的方法。
@Injectable({
providedIn: 'root'
})
export class TerritoryApiService {
private nameApi: string = 'territory';
constructor(private apiclient : ApiclientService) {}
public GetStaffTerritories(dateFrom: Date, dateTo: Date) {
let parameters = new Map();
parameters.set('dateFrom', dateFrom.toISOString());
parameters.set('dateTo', dateTo.toISOString());
return this.apiclient.doPostT<StaffTerritory[]>(this.nameApi, 'GetStaffTerritories', parameters);
}
}
TerritoryApiService 依賴於 ApiClientService,將包含 URL 的 HttpClient 和 AppConfig 傳遞給 ApiClientService。
@Injectable({
providedIn: 'root'
})
export class ApiclientService {
private apiurl: string;
constructor(private http: HttpClient, @Inject(APP_CONFIG) config: AppConfig) {
this.apiurl = config.apiEndpoint;
}
public doPostT<T> (url: string, method :string, parameters: Map<string,string> ) {
let headers = new HttpHeaders();
let httpParams = new HttpParams();
if (parameters != undefined) {
for (let [key, value] of parameters) {
httpParams = httpParams.append(key, value);
}
}
return this.http.post<T>(this.apiurl +'/v1/' + url + '/' + method, httpParams, {
headers: headers,
params: httpParams
})
}
}
const appConfig: AppConfig = {
apiEndpoint: environment.apiEndpoint
};
export const environment = {
production: false,
apiEndpoint: 'https://localhost:44390/api'
};
請告訴我如何正確准備測試(配置所有依賴項)? 因為現在我有兩種情況:
1.如果我只是在提供部分指定 ApiclientService ,則測試通過並出現錯誤,因為 appConfig 未定義(URL 變為 'undefined/v1/territory/GetStaffTerritories')
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [
TerritoryApiService,
ApiclientService,
{ provide: APP_CONFIG, useValue: APP_CONFIG }
]
});
如果我指定使用什么作為 ApiclientService,那么我需要顯式創建 HttpClient 並將其傳遞給構造函數。 在這種情況下,測試中會出現 post 方法未定義的錯誤。 那么需要創建HttpClient嗎?
常量 appConfig: AppConfig = { apiEndpoint: environment.apiEndpoint }; TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ TerritoryApiService, { provide: ApiclientService, useValue: new ApiclientService(httpClient, appConfig) }, { provide: APP_CONFIG, useValue: APP_CONFIG } ]});
完整的測試代碼
describe('TerritoryApiService', () => { let service: TerritoryApiService; let httpClient: HttpClient; let httpTestingController: HttpTestingController; const staffTerritoriesStub: StaffTerritory[] = [{ id: 1, name: 'StaffTerritory', regionCode: 29, createDate: new Date(), creatorId: 0, dateFrom: new Date(), dateTo: null, dateToSelect: new Date(), dateFromChanger: 0, dateToChanger: null, }]; const appConfig: AppConfig = { apiEndpoint: environment.apiEndpoint }; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ TerritoryApiService, { provide: ApiclientService, useValue: new ApiclientService(httpClient, appConfig) }, { provide: APP_CONFIG, useValue: APP_CONFIG } ] }); httpClient = TestBed.inject(HttpClient); httpTestingController = TestBed.inject(HttpTestingController); service = TestBed.inject(TerritoryApiService); }); afterEach(() => { httpTestingController.verify(); }); describe('#GetStaffTerritories', () => { beforeEach(() => { service = TestBed.inject(TerritoryApiService); }); it('should return expected heroes (called once)', () => { service.GetStaffTerritories(new Date(), new Date()).subscribe( staffTerritories => expect(staffTerritories).toEqual(staffTerritoriesStub, 'should return expected staffTerritories'), fail ); const req = httpTestingController.expectOne(appConfig.apiEndpoint + '/v1/' + 'territory' + '/' + 'GetStaffTerritories'); req.flush(staffTerritoriesStub); }); }); });
我認為您提供的AppConfig
錯誤,在您的情況下,我不會使用new ApiclientService(httpClient, appConfig)
模擬ApiclientService
,因為您正在使用HttpClient
提供HttpClientTestingModule
的實際實現。
嘗試這個:
describe('TerritoryApiService', () => {
let service: TerritoryApiService;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
const staffTerritoriesStub: StaffTerritory[] = [{
id: 1,
name: 'StaffTerritory',
regionCode: 29,
createDate: new Date(),
creatorId: 0,
dateFrom: new Date(),
dateTo: null,
dateToSelect: new Date(),
dateFromChanger: 0,
dateToChanger: null,
}];
const appConfig: AppConfig = {
apiEndpoint: environment.apiEndpoint // make sure environment.apiEndpoint is defined
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [
TerritoryApiService,
ApiclientService, // provide the actual ApiclientService since you have the dependencies
{ provide: AppConfig, useValue: appConfig } // this line needs to change to this
]
});
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
service = TestBed.inject(TerritoryApiService);
});
afterEach(() => {
httpTestingController.verify();
});
describe('#GetStaffTerritories', () => {
beforeEach(() => {
service = TestBed.inject(TerritoryApiService);
});
it('should return expected heroes (called once)', (done) => { // add done here to have a handle to let Jasmine know when we are done with our assertions
service.GetStaffTerritories(new Date(), new Date()).subscribe(
staffTerritories => {
expect(staffTerritories).toEqual(staffTerritoriesStub, 'should return expected
staffTerritories');
done(); // I would put a done here to ensure that the subscribe block was traversed
},
fail
);
const req = httpTestingController.expectOne(appConfig.apiEndpoint + '/v1/' + 'territory' + '/' + 'GetStaffTerritories');
req.flush(staffTerritoriesStub);
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.