Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PaulB's avatar
Level 20

API Testing Problem: The POST method is not supported + Invalid JSON was returned from the route.

Hello everyone,

I am testing API with Passport Auth and stuck with the issue. For some reason almost every Unit Test has an error simlar to this:

1) Tests\Feature\Auth\AuthenticationTest::authenticated_users_can_fetch_thier_user_data
Invalid JSON was returned from the route.
1) Tests\Feature\Auth\RegistrationTest::an_user_can_register_an_account
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The POST method is not supported for this route. Supported methods: GET, HEAD.

Postman is facing the same result. But if I run the application in the browser,everything works as expected.

Have somebody a clue, what it could be?

0 likes
6 replies
tykus's avatar

Invalid JSON was returned from the route means you are not returning a JsonResponse from the route - a response()->json($data) or returning an API Resource.

The POST method is not supported for this route means what it says; you have registered a GET route; but your test is attempting to POST to that URL

PaulB's avatar
Level 20

@tykus Thanks for replay.

Here is my code

Json Issue:

/** @test */
    function authenticated_users_can_fetch_thier_user_data()
    {
        $this->signIn($this->user);
        
        $response = $this->getJson('api/auth/user')->json();

        $this->assertEquals($this->user->email, $response['email']); 
    }    
public function user()
    {    
        return response()->json(request()->user()->load('company'));
    }

My Route don't trigger the user() method at all if I dd() there. Error happens before that, maybe in middleware.

POST Issue: The Route ist registered as POST.

Route::group([
    'prefix' => 'auth',
    'namespace' => 'Auth'
], function(){
    
    Route::post('/register', 'AuthController@register');    

    Route::group([
        'middleware' => 'auth:api'
    ], function(){
        
        Route::get('/user', 'AuthController@user');
        
    });
});
/** @test */
    function an_user_can_register_an_account()
    {        
       $this->registerAccount()->json();
        
       $this->assertCount(1, User::all());

        tap(User::first(), function($user){
            $this->assertEquals('John Doe', $user->name);            
            $this->assertEquals('[email protected]', $user->email);
            $this->assertTrue(Hash::check('secret', $user->password));            
        });
    }

 protected function registerAccount($overrides = [])
    {
        return $this->post('/api/auth/register', array_merge([
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' =>'secret',           
        ],$overrides));        
    }

The Problem seems to be somewhere in my configurations or middleware settings, but I'm not sure. Weird thing is, everythings still works in the bowser.

PaulB's avatar
Level 20

When I checkout the last working commit, for both cases I get NotFoundHttpException.

1) Tests\Feature\Auth\AuthenticationTest::authenticated_users_can_fetch_thier_user_data
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: 
tykus's avatar
tykus
Best Answer
Level 104

In the first case, does your signIn helper method use the TokenGuard - are you using auth:api in the actingAs helper; if not perhaps you are getting HTML response? You can dump the response by chaining the dump() method to the test request:

$response = $this->getJson('api/auth/user')->dump();

This will give you an indication of the issue, rather than a terse invalid JSON was returned message. In general, I prefer to use the assertJson, assertJsonStructure, assertJsonCount, assertJsonFragment and assertExactJsonmethods directly on the TestResponse class rather than getting the JSON from the response as an array, e.g.

function authenticated_users_can_fetch_thier_user_data()
{
    $this->signIn($this->user);
    
    $response = $this->getJson('api/auth/user');

    $response->assertJsonFragment([
        'email' => $this->user->email
    ]); 
}  

In the second case, can you instead postJson to ensure that the correct request headers are being set. I am not convinced this is the issue, but better to properly replicate your production environment.

1 like
PaulB's avatar
Level 20

This Json assertions are nice. I just found them in the documentaiton.

signIn method looks good. I can see auth()->user().

public function signIn($user = null)
    {
        $user = $user ?: create('App\User');

        $token = $user->createToken('TestToken', $this->scopes)->accessToken;        
        $this->headers['Accept'] = 'application/json';
        $this->headers['Authorization'] = 'Bearer '.$token;

        $this->actingAs($user, 'api');
        
        return $this;
    }

But if dump() the route, it throws me whole main html file as JSON.

PaulB's avatar
Level 20

@tykus Thanks for your advice. Authentication was wrong. Now it works.

Please or to participate in this conversation.