Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illuminate\Validation\ValidationException : The given data was invalid. Called when trying to get the json from a response while testing

I have the following test:

public function testStoreMemberValidation()
{
    $response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

    dd($response->json());
};

I am trying to assert that the response is of the form of a validation error. The controller method is as follows:

public function store(Request $request)
{
    $data = $request->validate([
        'name' => 'required|string',
        'age' => 'required|integer',
    ]);

    Member::create($data);
}

However, whenever I call any assertion which calls $response->json() (which is most of them) I get an exception:

Illuminate\Validation\ValidationException : The given data was invalid.

How can I perform assertions on this response without throwing this error?

Note, I am using Laravel 5.7.

like image 606
thodic Avatar asked Nov 02 '18 16:11

thodic


1 Answers

you have the withExceptionHandling() in your test, remove it and it should work.

$response = $this->withExceptionHandling()->post('/api/members', [
        "name" => "Eve",
        "age" => "invalid"
    ], ['X-Requested-With' => 'XMLHttpRequest']);

should be

$response = $this->post('/api/members', [
            "name" => "Eve",
            "age" => "invalid"
        ], ['X-Requested-With' => 'XMLHttpRequest']);
like image 167
Michael Nguyen Avatar answered Oct 13 '22 15:10

Michael Nguyen