Cas
Cas

Reputation: 395

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?

Upvotes: 5

Views: 6791

Answers (1)

pespantelis
pespantelis

Reputation: 15372

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');
    }
}

Upvotes: 5

Related Questions