1

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:

  • undefined and false
    • Error: Automatic conversion to JSON is not supported for response type.
  • null
    • response data is the string "null"

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);
    }
  );
jkyoutsey
  • 1,969
  • 2
  • 20
  • 31

2 Answers2

4

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

request.flush('', { status: 204, statusText: 'No Data' });
jkyoutsey
  • 1,969
  • 2
  • 20
  • 31
0

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.