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

1

8

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.

Cards answered 2/11, 2018 at 16:35 Comment(3)
Laravel does that by default, so it seems somewhere down the line (i.e. in a base test case class or something) you’ve added $this->withoutExceptionHandling.Aniseed
Also, you can use $this->postJson() to avoid adding the X-Requested-With header manually, and you can test for validation errors using $response->assertJsonValidationErrors('field_name').Aniseed
Thanks @MartinBean, changing it to $this->postJson() seems to have fixed it. I'm fairly sure I haven't called $this->withoutExceptionHandling() anywhere though.Cards
C
12

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']);
Clea answered 21/4, 2019 at 22:24 Comment(1)
Also ran into the same issue. Removing withExceptionHandling does clear the error. Is there a risk with that? I feel like the test should pass either way.Boatload

© 2022 - 2024 — McMap. All rights reserved.