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.

thodic
  • 2,229
  • 1
  • 19
  • 35
  • 1
    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`. – Martin Bean Nov 02 '18 at 16:45
  • 2
    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')`. – Martin Bean Nov 02 '18 at 16:47
  • Thanks @MartinBean, changing it to `$this->postJson()` seems to have fixed it. I'm fairly sure I haven't called `$this->withoutExceptionHandling()` anywhere though. – thodic Nov 02 '18 at 16:55

1 Answers1

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']);
Michael Nguyen
  • 1,691
  • 2
  • 18
  • 33
  • 2
    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. – Damon Feb 05 '20 at 19:23