1

I don't know if it is intended or not. But when I use a Reponse Code 204 in my Controller I get "Invalid JSON was returned from the route" in PHPunit.

But if I change the Response Code to 201, everything works fine... Why?

protected function output($title, $status = 201)
{
    return response([
        'title' => $title,
        'offers' => $this->popular,
    ], $status);
}

$this->output('Empty', 204); //Here is the error

In my test

/** @test */
public function popular_can_fetch_food_lists() {
    $result = $this->json('post', route('popular', [
        'type' => $this->food->type,
        'id' => $this->food->id
    ]))->json();
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Philipp Mochine
  • 4,351
  • 10
  • 36
  • 68
  • 1
    204 means **no content**. Are you trying to get json out of no content or I get it wrong? – vahdet Jun 16 '18 at 18:10
  • @vahdet Oh... but which Response Code would you take if you response is an Empty Array? – Philipp Mochine Jun 16 '18 at 19:09
  • Empty array is still *something*. Literally nothing is set in the response body for 204. What is best fit for you: You send a `POST` and seeing this [doc](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201), "The common use case of this status code (201) is as the result of a POST request.". So, 201 must be perfectly legal for your purpose. – vahdet Jun 17 '18 at 10:10

1 Answers1

1

If you take a look at https://httpstatuses.com/204 you can read:

A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.

So in case you are using 204 for anything in fact no content will be in response.

So you shouldn't probably run ->json() in your test. You should only verify if status code is 204

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291