1

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.

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

My service override the response and is 400. I ll try the header Accept but the response is to validate de information structure. not just the header

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.