[英]How do I test the response of this service function in Angular?
我的服務中有以下 function
import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; import { APP_CONST } from '../app-const'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) { } getLandingData(): Observable<any> { return this.http.get(this.landingApiEndPoint+this.api.landing_uri).pipe( map((response: any) => { console.log('Res ', response); return response; }) ); }
對於這個 function,我寫了這個測試用例:
it('should get Landing Data', (done: DoneFn) => { const names = [{name: 'a'}, {name: 'b'}]; service.getLandingData().subscribe((res)=>{ expect(res).toEqual(names); console.log("Landing "+res); console.log("Landing names"+names); done(); }) });
但我不斷收到此錯誤: Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
我嘗試設置默認超時間隔,但沒有運氣。 我正在使用jasmine 4.2.0 。 請讓我知道如何正確測試。
您需要在測試中導入HttpClientTestingModule
模塊。 然后您需要模擬 httpClient 或使用HttpTestingController
來模擬請求。
例如:
describe('TestSuite', () => {
let service: Service;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [Service]
});
service = TestBed.inject(Service);
httpMock = TestBed.inject(HttpTestingController);
});
it('should get Landing Data', (done: DoneFn) => {
const names = [{ name: 'a' }, { name: 'b' }];
service.updateAlias().subscribe((res)=>{
expect(res).toEqual(names);
console.log("Landing ", res);
console.log("Landing names", names);
done();
});
httpMock
.expectOne('http://landing-page.com/url')
.flush(names);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.