Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 PHPUnit - Invalid JSON was returned from the route

Routes

Route::group(array('prefix' => 'api'), function() {
   Route::resource('test', 'TestController', array('only' => array('index', 'store', 'destroy', 'show', 'update')));
});

Controller

public function store(Request $request) {
    return response()->json(['status' => true]);
}

Unit Class

public function testBasicExample() {
    $this->post('api/test')->seeJson(['status' => true]);
}

PHPUnit result:

1) ExampleTest::testBasicExample

Invalid JSON was returned from the route.

Perhaps an exception was thrown? Anyone see the Problem?

like image 546
Cas Avatar asked Dec 08 '15 10:12

Cas


1 Answers

The problem is the CSRF Token.

You could disable the middleware by using the WithoutMiddleware trait:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
    use WithoutMiddleware;

    //
}

Or, if you would like to only disable middleware for a few test methods, you may call the withoutMiddleware method from within the test methods:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->withoutMiddleware();

        $this->visit('/')
             ->see('Laravel 5');
    }
}
like image 73
Pantelis Peslis Avatar answered Sep 23 '22 09:09

Pantelis Peslis