Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I receive "CSRF token mismatch" while running tests in laravel?

I want to run my tests without receiving "CSRF token mismatch" exceptions. In the laravel documentation is noted that:

The CSRF middleware is automatically disabled when running tests.

the line of code where the exception is thrown looks like this:

$response = $this->json('POST', route('order.create'), [
     'product_id', $product->id
]);

and for running tests I am working in my zsh terminal:

php artisan test --env=testing

This is my test class:

<?php

   namespace Tests\Feature;

   use Illuminate\Foundation\Testing\RefreshDatabase;
   use Illuminate\Foundation\Testing\WithFaker;
   use Illuminate\Foundation\Testing\WithoutMiddleware;
   use Tests\TestCase;

  class SessionCartTest extends TestCase
  {
      public function testExample()
      {
          $product = \App\Product::inRandomOrder()->first();
          $response = $this->postJson(route('order.insert'), [
              'product_id' => $product->id,
          ]);
          $response->assertStatus(200); // here I receive 419
      }
  }

What am I doing wrong and how could I fix this? I am using laravel 7.

like image 727
Mihai Crăiță Avatar asked Apr 09 '20 06:04

Mihai Crăiță


2 Answers

I ran into this problem x times now and each time I fix it by running: php artisan config:clear

like image 170
Daniel Katz Avatar answered Oct 03 '22 12:10

Daniel Katz


Probably the APP_ENV is not being set to testing.

You can set a ENV variable in the command line by preceding the php command.

So on your case set the environment to testing and run the artisan command by:

APP_ENV=testing php artisan test
like image 36
Diogo Gomes Avatar answered Oct 03 '22 11:10

Diogo Gomes