chaotic's avatar

A facade root has not been set when writing pest test

in my laravel app i have a simple http test that have written in pest

it('test http', function () {

    $post= [
            {some data}
        ];

    $expectedStatusCode = 200;

    $response = Http::withHeaders([
        'Authorization' => 'Bearer {token}',
    ])->post({url}, $post);

    expect($response->status())->toBe($expectedStatusCode);
}

when i execute the code it return me this error RuntimeException: A facade root has not been set. How can I solve it?

0 likes
2 replies
vincent15000's avatar

Do you have more details about the error ?

In your test, I see that you are using the Http facade. Have you declared it ?

use Illuminate\Support\Facades\Http;
newbie360's avatar

change to use $this->

    $response = $this->withHeaders([
        'Authorization' => 'Bearer {token}',
    ])->post({url}, $post);

if in composer.json have installed "pestphp/pest-plugin-laravel": "......",

you can avoid use $this->

<?php

use function Pest\Laravel\withHeader;

it('test http', function () {

    $post= [
            {some data}
        ];

    $expectedStatusCode = 200;

    $response = withHeaders([
        'Authorization' => 'Bearer {token}',
    ])->post({url}, $post);

    expect($response->status())->toBe($expectedStatusCode);
}

so it means you can without use $this->

<?php

use function Pest\Laravel\get;
use function Pest\Laravel\post;

test('returns a successful response', function () {
    get('/')->assertOk();

    post('/')->assertOk();
});
1 like

Please or to participate in this conversation.