phplaraveltestingintegration-testinglaravel-dusk

Detecting when Laravel Dusk is running


Often in Laravel I need to detect the environment to avoid triggering certain code while running tests, like logging or sending an email:

if (!app()->environment("testing")) {
    Mail::to($email)->queue(new WelcomeEmail($transaction->id));
}

This works fine when the environment is set to testing in 3 of my 4 environment files (local and CI/CD unit tests, Dusk on CI/CD), but my .env.dusk.local file - which I need to run Laravel Dusk locally - has a local environment, and in these cases Dusk triggers the sending of emails, logs, etc.

The cleanest solution I can see for this would be to detect whether Dusk is running in any environment - I'm aware there's an app()->runningUnitTests() method, but don't know of an equivalent for Dusk.


Solution

  • Dusk will check for a file .env.dusk.<environment>.

    Using local environment as an example, it will check .env.dusk.local. Setting APP_ENV=dusk in that file will permit you to add checks like if(app()->environment('dusk')) where necessary.

    As noted in the comments, though, for the specific example of sending mail or logging, you're generally better off overriding MAIL_DRIVER or LOG_CHANNEL to something suitable for testing, like MAIL_DRIVER=log or LOG_CHANNEL=daily, so you can still test that functionality without sending actual emails.