I want to test use of an endpoint that will return true
or false
as the response. Not 'true'
but a boolean value of true
. I am using the @angular/common/http/testing
module. For other response values I can use TestResponse.flush(value)
, but this does not work for a boolean
value. Instead, the testing module complains
Automatic conversion to JSON is not supported for response type.
Here is my test code:
const FLUSH_OK = {status: 200, statusText: 'Ok'};
//.. describe...
it('should work', async(() => {
service.myFunction().subscribe((data) => { // my Function returns Observable<boolean>, the real endpoint returns a true/false boolean
expect(data).toEqual(true);
});
// this fails: Failed: Automatic conversion to JSON is not supported for response type.
httpMock.expectOne((req) => {
return req.url === MY_URL;
}).flush(true, FLUSH_OK);
// this also fails: Expected 'true' to equal true.
// httpMock.expectOne((req) => {
// return req.url === MY_URL;
// }).flush('true', FLUSH_OK);
}));
flushlink. Flushes any pending microtasks and simulates the asynchronous passage of time for the timers in the fakeAsync zone by draining the macrotask queue until it is empty.
flush()linkResolve the request by returning a body plus additional HTTP information (such as response headers) if provided. If the request specifies an expected body type, the body is converted into the requested type. Otherwise, the body is converted to JSON by default.
beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite. In this test suite, beforeEach is used to create a testing module using the TestBed object and declares any components that would be used in this testing module.
Using the HttpClientTestingModule and HttpTestingController provided by Angular makes mocking out results and testing http requests simple by providing many useful methods for checking http requests and providing mock responses for each request.
Using the event
method rather than flush
allows you to specify the type of the response body.
const req = httpMock.expectOne('some-url');
req.event(new HttpResponse<boolean>({body: true}));
You could optionally also set other properties such as status
or statusText
.
HttpResponse docs
Original answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With