Summer Sale! All accounts are 50% off this week.

bbkbbk's avatar

Testing forms

Hi, I am trying to find the best method for testing forms in Laravel. I'm using Inertia and Laravel Fortify for user accounts.

If I run what I'm trying to test in the web browser it works as expected, however, when I run the test I'm getting a 419 status response with the error being: CSRF token mismatch.

According to documentation for Inertia in Laravel it handles CSRF protection for us (which I guess is why running this manually in the browser works): https://inertiajs.com/csrf-protection

Here's my current code to test registering an user:

        $response = $this->get('/register')
            ->assertStatus(200);

        $response = $this->json('POST', '/register', [
            'name' => 'Example Name',
            'email' => '[email protected]',
            'password' => 'password',
            'password_confirmation' => 'password'
        ]);

        $response->assertCreated();

I 'm also not sure if this is the correct way to test a POST request from a form, so if this is wrong please suggest a better method to write a test for this, or if it is better to use Laravel Dusk to perform this kind of test by simulating the user filling out the form.

To find out it was a CSRF issue I ran:

$response->dump();

in the test.

Any suggestions are much appreciated.

0 likes
1 reply
pixelfix's avatar

Hey, I also had the same problem. My tests were working fine one day and the next I started getting 419 errors. The browser still worked perfectly fine. I am also not sure if this is the correct way to test forms in Inertia, but I am testing it in a similar way.

I got my tests to work again just by running php artisan config:clear. I hope it helps.

Please or to participate in this conversation.