Solvedangular Testing - HttpTestingController throws errors for valid JSON
✔️Accepted Answer
work-a-round:
const req = httpMock.expectOne('some-url');
req.event(new HttpResponse<boolean>({body: true}));
instead of req.flush(true)
Other Answers:
The above workaround simply masks the issue, since no response is actually resolved without calling 'flush' or 'error'. The reason it will appear to succeed is simply due to the specific nature of the testing scenario, for example:
it ("should verify that user is authenticated", () => {
// calls underlying http post at 'api/account/isAuth'
service.isAuth().then(response => {
// does not execute, and so test defaults to success
console.log("success!");
expect(response).toBe(true);
});
const req = backend.expectOne("api/account/isAuth");
req.event(new HttpResponse<boolean>({ body: true }));
});
As stated in the docs, 'event' is used for sending HttpEvent responses for things like progress updates, and as such doesn't appear to have much use unless 'flush' or 'error' is used to call 'complete' or 'error' on the underlying observable.
The solution I used was simply to use a 'truthy' value in place of the boolean. Any underlying checks against a boolean value can usually be resolved within conditional statements this way, and so any logic checks in the underlying method code should be covered in this scenario:
it ("should verify that user is authenticated", () => {
service.isAuth().then(response => {
console.log("success!"); // underlying check successfully calls
expect(response).toBe(true); // response is 'true', since underlying check against 1 is 'true'
});
const req = backend.expectOne("api/account/isAuth");
// underlying post response body should be 'true', but 1 is truthy, and so will work in most scenarios
req.flush(1);
});
Changing the one to zero in the above test causes the test to fail, and as such achieves the exact same behaviour as I would have expected from using a boolean value in the body of the response.
Angular 8... same issue :-(
I'm submitting a...
Current behavior
HttpTestingController
throws exception for valid JSON.Failed: Automatic conversion to JSON is not supported for response type.
error(see https://github.com/angular/angular/blob/master/packages/common/http/testing/src/request.ts#L159)
But according to http://www.json.org/ valid JSON is:
Expected behavior
It should not throw exception and use value as JSON response of http call.
Minimal reproduction of the problem with instructions
Environment