orest's avatar
Level 13

remove fake notifications

In the majority of my tests in Dusk, I want to run Notification:fake() and in order to avoid writing it in every test file, I moved it to DuskTestCase

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication;

    public function setUp(): void
    {
        parent::setUp();
        Notification::fake();
    }
}

However, there are few tests that I actually need to send real notifications.

Is there a way to swap the fake notification with the real ?

1 like
5 replies
orest's avatar
Level 13

I think i found a solution, which is to unregister the ChannelManager dependency from the container, which returns the NotificationFake class.

unset(app()[ChannelManager::class]);
2 likes
juanpferreira's avatar

The solution suggested by @orest worked for me in the case of Notifications, but I tried it for reverting Http::fake() (using \Illuminate\Http\Client\Factory::class instead of ChannelManager::class) and it didn't seem to work. But I found this solution which worked for both.

Notification::swap(null);
Http::swap(null);
1 like
kevinbui's avatar

I have read the source code a bit, the Notification::swap() method and the Illuminate\Support\Facades\Facade class.

All the mentioned solutions might work, but I believe this is the correct way to to get a real instance again:

use Illuminate\Support\Facades\Notification;
use Illuminate\Notifications\ChannelManager;

if (Notification::isFake()) {
	$name = ChannelManager::class;

    Notification::clearResolvedInstance($name);
    Notification::getFacadeApplication()?->forgetInstance($name);
}

Ideally this should be a method of the Illuminate\Support\Facades\Facade class. I am thinking about contributing a real method to Laravel that do the same.

namespace Illuminate\Support\Facades\Facade;

abstract class Facade
{
    public static function real(): void
    {
        if (static::isFake()) {
            $name = static::getFacadeAccessor();

            static::clearResolvedInstance($name);

            static::$app?->forgetInstance($name);
        }
    }
}

Please or to participate in this conversation.