Marco Feregrino
Marco Feregrino

Reputation: 663

assert Json Validation Errors does not work

I am not an expert and I could not find anything about my error. I hope someone can help me to understand my error.

I am trying to test the validation of the required attributes of a POST request in Laravel.

TEST

I am using the assertJsonValidationErrors method to validate the JSON errors from my controller.

/** @test */
public function name_email_password_required_in_creation()
{
    $response = $this->post('/users', [
        'contact' => '545678987'
    ]);
    $response->assertJsonValidationErrors(['name','password','email']);
}

Controller

$validator = Validator::make($request->all(),[
        'name' => 'required',
        'email' => 'required|unique:users,email',
        'password' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->errors(), 400);
    }

Error:

1) Tests\Feature\UsersTest::name_email_password_required_in_creation Failed to find a validation error in the response for key: 'name'

Response does not have JSON validation errors. Failed asserting that an array has the key 'name'.

I applied inside the test a

dd($response->getContent()); to see what is happening and in the response is:

"{"name":["The name field is required."],"email":["The email field is required."],"password":["The password field is required."]}"

It seems to be a string but I don't know if it is causing the error, because the JSON contains the key fields errors.

I do know how to solve it. Thanks in advance.

Upvotes: 1

Views: 4294

Answers (1)

bryceandy
bryceandy

Reputation: 176

Instead of this:

$response = $this->post('/users', [
    'contact' => '545678987'
]);

Use headers to accept json like this:

$response = $this->json('POST', '/users', ['contact' => '545678987'],
    ['Accept' => 'application/json']
);

Also for validation errors the response code is 422, so use:

if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}

Upvotes: 1

Related Questions