'Best approach for testing a http post service within a void method?
I am pretty new into unit testing and I am struggling to know how to test a void method in service that contains an http post. I am not looking for code solution on spec.ts, just any clue or idea to get the best approach for this. What I have read on internet it was not very useful at the moment for me. Thank you very much in advance, you guys are an awesome community!
So this is my member-add.service.ts:
import { Injectable } from "@angular/core";
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
} from "@angular/common/http";
import { MemberContact } from "src/app/models/member-contact/member-contact.interface";
import { throwError, catchError } from "rxjs";
import { Router } from "@angular/router";
@Injectable({
providedIn: "root",
})
export class MemberAddService {
private _membersUrl: string = "http://localhost:8080/api/members";
private _http: HttpClient;
private _newMember: MemberContact;
constructor(http: HttpClient, private router: Router) {
this._http = http;
}
postMemberContactInfo(
memberContactInfo: MemberContact,
callback: Function,
errorCallback: Function
) {
this._http
.post<MemberContact>(this._membersUrl, memberContactInfo, {
headers: new HttpHeaders({ "Content-Type": "application/json" }),
responseType: "json",
observe: "body",
})
.subscribe({
next: (value) => {
this._newMember = value;
},
complete: () => {
this.router.navigate([`/members/${this._newMember.id}`], {
state: this._newMember,
});
callback(this._newMember);
console.log(this._newMember);
},
error: (error) => {
catchError(this.handleError);
errorCallback(error);
console.log(this._newMember);
},
});
}
private handleError(error: HttpErrorResponse) {
if (error.status == 0) {
// A client-side or network error occurred. Handle it accordingly.
console.error("An error occurred:", error.error);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(
`Backend returned code ${error.status}, body was: `,
error.error
);
}
// Return an observable with a user-facing error message.
return throwError(
() => new Error("Something bad happened; please try again later.")
);
}
}
As you can see, there is an only method which sets a callback to the component if the new member insertion is succesful or not. How I can test this if nothing is returned?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
