It sounds like you're encountering a TokenMismatchException when running your Pest tests in a Laravel application using Jetstream with Inertia and Vue. This typically happens because the CSRF token is not being handled correctly in your tests.
Here are some steps to resolve this issue:
-
Disable CSRF Middleware for Testing: One approach is to disable the CSRF middleware during testing. This can be done by modifying the
App\Http\Middleware\VerifyCsrfTokenmiddleware to exclude the routes during testing. -
Set CSRF Token in Tests: Another approach is to ensure that the CSRF token is correctly set in your tests.
Solution 1: Disable CSRF Middleware for Testing
You can modify the VerifyCsrfToken middleware to disable CSRF verification when running tests.
// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
//
];
public function handle($request, Closure $next)
{
if (app()->environment('testing')) {
return $next($request);
}
return parent::handle($request, $next);
}
Solution 2: Set CSRF Token in Tests
Ensure that your tests are correctly setting the CSRF token. You can do this by including the CSRF token in your requests.
Here is an example of how you can set the CSRF token in your Pest tests:
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Session;
uses(RefreshDatabase::class);
it('can perform a post request', function () {
$response = $this->post('/your-endpoint', [
'_token' => csrf_token(),
// other request data
]);
$response->assertStatus(200);
});
Example Test with CSRF Token
Here is a more complete example of a Pest test that includes the CSRF token:
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Session;
uses(RefreshDatabase::class);
it('can perform a post request', function () {
// Start a session to generate a CSRF token
Session::start();
$response = $this->post('/your-endpoint', [
'_token' => csrf_token(),
'key' => 'value',
]);
$response->assertStatus(200);
});
Additional Tips
- Ensure that your test environment is correctly set up and that you are using the correct environment configuration.
- If you are using Laravel Sail, make sure your test database is correctly configured and accessible.
By following these steps, you should be able to resolve the TokenMismatchException and get your tests passing.