iamripespoon's avatar

Sending Header Content-Type with Laravel 5.4 Test Request

Hello, i'm very new to tests in Laravel and i'm trying to build my first one, but i've hit a bit of a wall.

I'm trying to setup a series of tests for my API.

The API insists that you must provide the header Content-Type so it knows in which format to return the response in.

However, when i'm creating my test and i try and send the Content-Type in the header, it's not picking up on the API that i've actually sent the header.

So when I use:


$this->assertEquals('application/json', $response->headers->get('Content-Type'));

It just comes back as false.

This is the request i've built as a baseline.


$response = $this->json('POST', '/submit', ['name' => 'Sally'], [], [], ['Content-Type' => 'application/json']);

I get the following response:


1) Tests\Feature\ForceDeclineTest::testValidationError
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'application/json'
+'text/html; charset=UTF-8'

Can anyone help me as to how i send the Content-Type header in the test request?

0 likes
1 reply
Lars-Janssen's avatar
$response = $this->json('POST', '/submit', ['name' => 'Sally'], ['Content-Type' => 'application/json']);

Try that but by default the correct headers should already being set.

public function json($method, $uri, array $data = [], array $headers = [])
{
    $files = $this->extractFilesFromDataArray($data);

    $content = json_encode($data);

    $headers = array_merge([
        'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
        'CONTENT_TYPE' => 'application/json',
        'Accept' => 'application/json',
    ], $headers);

    return $this->call(
        $method, $uri, [], [], $files, $this->transformHeadersToServerVars($headers), $content
    );
}

Please or to participate in this conversation.