'Laravel Json test with Bearer authentication

I'm writing a simple test to assert if an api endpoint response returns with 200 status.

My api got Bearer authentication through sanctum middleware.

My test function is

    public function testExample()
    {
//        $response = $this->withHeader('Authorization' , 'Bearer 1|IJleXxjHgr8RaiP3Q9atJRtVCZHZKQQqBXW8NPdn')
//                            ->getJson('/api/breeds/cat/high');
        $response = $this->getJson('/api/breeds/cat/high', ['Authorization' => 'Bearer longtoken']);
        $response->assertStatus(200);
    }

routes/api.php;

> Route::middleware('auth:sanctum')->group(function () {
>     Route::get('/breeds/{animal_type}/{name}', ListBreeds::class)->name('breed.list'); });

This test returns me with 403 / Not Authorised response. If I use the same token and headers in Postman the route works fine.

what is it I'm doing wrong?

Thanks in advance.



Solution 1:[1]

It should be like that:

$response = $this->withHeaders([
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . 'abc',
    ])->getJson('/api/breeds/cat/high');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dust_bg