laravelhttplaravel-5phpunithttp-status-code-204

Why do I get a "Invalid JSON" when Status Code 204?


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

Solution

  • 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