[英]How to write unit test for subscribe callback of a service
我正在學習如何在Angular中編寫單元測試。 我創建一個具有方法sendToServer的httpService。 每個組件都使用它向服務器發送請求:
sendToServer(method, url, body, header, onSuccessCallback, onErrorCallback?);
這是我的組件
export class LoginComponent implements OnInit {
constructor(private http: HttpService) {
}
data ;
ngOnInit() {
this.getToken();
}
getToken(){
this.http.sendToServer("GET", "/api/tokent",{}, null, data=>{
this.data = data;
});
}
}
這是我的單元測試代碼:
it("should call getTokent and return data", fakeAsync(() => {
const response = "abc";
component.getToken();
spyOn(service, 'sendToServer').and.returnValue(of(response));
tick();
fixture.detectChanges();
expect(component.data).toEqual(response);
}));
如何測試http.senntoServer的回調函數
您需要在模擬的DataService中觸發回調函數,而不是返回固定值。 顧名思義,使用returnValue
可以在方法被調用且不執行其他任何操作時返回值。
在您的情況下,您要使用的是callFake
然后在該偽函數中觸發觸發器。
組件規格
it('test callback', () => {
spyOn(TestBed.get(DataService), 'sendToServer').and.callFake((parm1: string, param2: string, param3: any, param4: any, callback: (data) => {}) => {
callback('DATA_RESULT');
})
fixture.detectChanges();
expect(component.data).toEqual('DATA_RESULT');
});
這是一堆堆炸彈 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.