Reputation: 79
I am learning about how to write unit test in Angular. I create a httpService having method sendToServer. Every component uses it to send request to server:
sendToServer(method, url, body, header, onSuccessCallback, onErrorCallback?);
Here is my component
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;
});
}
}
Here is my unit test code:
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);
}));
How can I test in callback function of http.senntoServer
Upvotes: 2
Views: 2370
Reputation: 1659
You need to trigger your callback function inside the mocked DataService instead of returning a fixed value. Using returnValue
just as the name suggests, returns the value if the method gets called and does nothing else.
In your case what you would want to use is callFake
and inside that fake function you can then trigger your callback.
component.spec.ts
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');
});
Here is a stackblitz.
Upvotes: 1