18

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.

5
  • Why are you using an artisan command to run the tests? What happens when you run phpunit on your console? Are you sure that you are getting a CSRF exception? Commented Apr 9, 2020 at 7:56
  • Its the same when running phpunit. I am dumping the response and I see what's inside, also the HTTP error code is 419. Commented Apr 9, 2020 at 8:31
  • Can you include your test class? Commented Apr 9, 2020 at 10:32
  • @DigitalDrifter I added my test class in the question Commented Apr 9, 2020 at 13:25
  • in the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken constructor somehow sets the $app->env to "local" instead of "testing" Commented Apr 9, 2020 at 13:30

5 Answers 5

64

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

Sign up to request clarification or add additional context in comments.

4 Comments

I need to make a mug that says this or something. So many times i've found some very strange behavior and this has fixed it.
Found so many strange behavior. This saved my OT. Thanks!
Thanks so much. I saw red all across the board and panicked...
This worked for me, but what does it do?
24

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

1 Comment

Same. Indeed, the problem is the environment not being set correctly, even though I added it explicitly. Something is overwriting it... before calling the Middleware
2

When you are running tests on Docker where the APP_ENV is hard coded with other values than testing (dev, local) in docker-compose.yaml file, phpunit cannot execute tests properly. You will need to delete the all APP_ENV in docker files.

Comments

1

Your data array is wrong. Try the following change:

$response = $this->postJson(route('order.insert'), [
      'product_id' => $product->id, // use the arrow notation here.
 ]);

5 Comments

yes, that's a typo, fixed, but I still get the exception "Expected status code 200 but received 419. Failed asserting that false is true." Maybe is something super obvious that I miss..
that's how my route is defined in web Route::post('/order', 'OrderController@insert')->name('order.insert');
Try running php artisan cache:clear before running your tests.
I fixed it, it was from the config cache. I also had to remove the lines from phpunit.xml regarding DB_CONNECTION sqlite and DB_DATABASE. Thanks for all the hints!
To be clear, its was the php artisan config:clear command which did the trick for me
1

This works by setting a custom csrf-token

$this
   ->withSession(['_token' => 'bzz'])
   ->postJson('/url', ['_token' => 'bzz', 'other' => 'data']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.