Laravel Testing — How to Fix the “A Facade Root Has Not Been Set” Problem

Emeka Mbah
2 min readDec 8, 2023

--

Solution for Pest Tests:

To resolve this issue, the following line was added to the tests/Pest.php file:

<?php

/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/

uses(Tests\TestCase::class)->in('Unit', 'Feature');

This addition ensures that the necessary Laravel components are properly initialized when running tests, thereby addressing the “A facade root has not been set” error.

Solution for PHP Unit:

If you exclusively rely on PHPUnit, ensure your test extends Tests\TestCase, incorporating the CreatesApplication trait. This trait is responsible for setting up the test environment.

In tests/TestCase.php

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Testing\TestResponse;

abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}

Need more details about this issue? Read on…

When encountering the error message “A facade root has not been set” in Laravel, it generally indicates an issue with the configuration of a Laravel facade. This problem can specifically arise when the Laravel application is not adequately booted, especially during test execution.

I recently encountered and resolved this issue while working on a Laravel PEST test scenario. Here’s a detailed walkthrough of the problem and its solution.

Problem Description:

The error manifested itself after introducing the Laravel\Scout\Searchable trait to a model, as illustrated in the code snippet below:

use Illuminate\Foundation\Auth\User as Authenticatable;

final class User extends Authenticatable
{
use Searchable;
}

And a Pest test was implemented like so:

// tests/Unit/UserTest.php

use App\Models\User;

it('can determine if it has a password set', function () {
$user = new User(['password' => 'foo']);
expect($user->hasPassword())->toBeTrue();
});

However, the test failed with the following error:

• Tests\Unit\UserTest > it can determine if it has a password set
PHPUnit\Framework\ExceptionWrapper
A facade root has not been set. at vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:352
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}

What is Pest?
https://pestphp.com/

--

--

Emeka Mbah
Emeka Mbah

Written by Emeka Mbah

Emeka is a seasoned software developer passionate about contributing to open-source projects.

Responses (2)