Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@angular/common/http/testing TestRequest.flush a boolean value

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);

}));
like image 561
Jeff Avatar asked Jan 31 '18 14:01

Jeff


People also ask

What does flush do in angular testing?

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.

What is request flush?

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.

What is beforeEach in angular testing?

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.

What is HttpClientTestingModule?

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.


1 Answers

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

like image 121
Louis Avatar answered Sep 28 '22 21:09

Louis