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

Rretzko's avatar
Level 15

Form Testing and CSRF token

Hi - I'm trying to set up a test for a log-in form submission, although I think I'd hit this problem with testing any form. When I run the test I get the error "Illuminate\Session\TokenMismatchException: CSRF token mismatch". For those testing guru's out there: a) am I doing something wrong or b) how do I correctly fake the csrf token ? Here's the test function:

public function test_user_can_log_in()
    {
        $this->withoutExceptionHandling();

        $this->post(uri: action([LoginController::class,'show'],[
            'email' => '[email protected]',
            'password' => 'password',
		  '_token' =>csrf_token(),
        ]))
        ->assertSuccessful();
    }

and the Controller's "show" function:

public function show(Request $request)
    {
        $inputs = $request->validate(
            [
                'email' => ['email','required'],
                'password' => ['string','required'],
            ]
        );

        return view('welcome');
    }

Thanks for your help!

0 likes
13 replies
Sinnbeck's avatar

No need to add the csrf token. Try removing it

Also you it seems wrong that show is a post route? A post route is for storing data, not showing a view. Seems you have mixed up 2 routes

Rretzko's avatar
Level 15

Thanks for the quick response. Originally I did not have the csrf token in the array and am hitting the same error. I've removed it:

public function test_user_can_log_in()
    {
        $this->withoutExceptionHandling();

        $this->post(uri: action([LoginController::class,'show'],[
            'email' => '[email protected]',
            'password' => 'password',
        ]))
        ->assertSuccessful();
    }

and still getting the same error:

Illuminate\Session\TokenMismatchException : CSRF token mismatch.
 C:\xampp\htdocs\dev\tdrlib\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:85
...
 C:\xampp\htdocs\dev\tdrlib\tests\Feature\LoginPageTest.php:33

Line 33 is the 'email' => '[email protected]' line. I probably should have this as an __invoke function in the controller rather than show, but here's my route:

Route::post('library/login', [App\Http\Controllers\Libraries\Auth\LoginController::class, 'show'])
    ->name('librarylogin');

Thanks again for your help!

Rretzko's avatar
Level 15

Thanks @MohamedTammam but I'm still hitting the same error.

public function test_user_can_log_in()
    {
        $this->withoutExceptionHandling();

        $this->post(route("librarylogin"),[
            'email' => '[email protected]',
            'password' => 'password',
        ])
        ->assertSuccessful();

    }
Rretzko's avatar
Level 15

Some additional info: If I add the path to the $except array int the VerifyCsrfToken middleware, the test passes.

protected $except = [
        "http://localhost/library/login?email=rick%40mfrholdings.com&password=password",
    ];

I'm using this as a workaround, but it surely can't be the way this is designed. I'm sure I've done something stupid, but I can't see it.

Rretzko's avatar
Level 15

@MohamedTammam - In trying to remove complexity, I've simplified the command to the specific uri and arguments:

 $this->post('http://localhost/library/login',
            [
                'email' => '[email protected]',
                'password' => 'password',
            ])
            ->assertSuccessful();

I still hit the same error.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Maybe you cached stuff in dev (never cache in dev or testing)

Try

php artisan config:clear
//or
php artisan optimize:clear
1 like
Rretzko's avatar
Level 15

@Sinnbeck , Thanks. Like I said: Maybe I did something stupid. That solved the problem. I appreciate your time and patience!

Please or to participate in this conversation.