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

Emeka Mbah
2 min readDec 8, 2023

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

Subsequently, a PEST test was implemented:

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

Solution:

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

uses(
Tests\TestCase::class,
)->in('Unit'); //refers to Tests\Unit

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.

By incorporating this solution, the PEST test was executed successfully, confirming that the problem had been effectively resolved.

Feel free to integrate this approach into your Laravel project to tackle similar issues related to the “A facade root has not been set” error during testing.

Not Using PEST?
If you exclusively rely on PHPUnit, make sure that your test extends Tests\TestCase, which incorporates the CreatesApplication trait. This trait is responsible for setting up the test environment.

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

--

--

Emeka Mbah

I am a seasoned software developer who loves writing code in PHP, Laravel, and Javascript