jkyoutsey
jkyoutsey

Reputation: 2041

How do I unit test an Angular HttpClient 204 response?

Our REST service returns 204's for a no data scenario. But I cannot figure out how to test for this scenario.

it('can handle no data', (done) => {
  const testData = service.getDummyData();
  service.dataChanged$.subscribe(
    (data: Data[]) => {
      expect(data).toBeUndefined();
      done();
    }
  );
  service.getData();
  const request: TestRequest = backend.expectOne(MyService.URL);
  request.flush(undefined, { status: 204, statusText: 'No Data' });
});

I've tried passing:

So, what should I be passing to the flush function to send an empty response? I test the response in the service (simplified):

this.http.get<Data[]>(MyService.URL)
  .first().subscribe(
    (data: Data[]) => {
      if (data) {
        this.dataChanged$.next(data);
      } else {
        Logger.error(MyService.name, 'getData', 'No data.');
        this.dataChanged$.next(undefined);
      }
    },
    (error: Error) => {
        Logger.error(MyService.name, 'getData', error.message);
      this.dataChanged$.next(undefined);
    }
  );

Upvotes: 1

Views: 5139

Answers (2)

Valentino Filipetto
Valentino Filipetto

Reputation: 11

It is probably fine to write

expect(data).toBeNull();

in fact you can very well write a variable with type void and value null. And then the request should be:

request.flush(null, { status: 204, statusText: 'No Data' });

Passing "" to flush would also give Error: Automatic conversion to JSON is not supported for response type.

Upvotes: 0

jkyoutsey
jkyoutsey

Reputation: 2041

So, the simple answer is, pass '' to flush():

request.flush('', { status: 204, statusText: 'No Data' });

Upvotes: 4

Related Questions