Testing if Dusk environment matches Browser environment

Laravel Dusk brings e2e tests into Laravel and that means a full browser in a separate operating system process running your tests. No more mocks, no more implementation swapping. When Google Chrome hits your application after being opened by Dusk, it will go through the complete request lifecycle (Entrypoint, Service Providers, Routes, Middlewares, Form Reqeusts, Controllers).

Because of this whole separate process concept, setting up Dusk environment might be a little confusing, specially if you use php artisan serve as the HTTP Server for your Dusk tests (it will cache .env before Dusk had a change to swap it). I decided to write a custom assertion that will tell me if the Browser is using the correct environment. This allows me to check if my code is not running on the environment that I wanted it to run.

The Route

First thing to achieve this is to add a Route that will return the environment being used by the application. I added this route right after registering DuskServiceProvider

$this->app->register(DuskServiceProvider::class);

// Add route that will return the environment name
Route::get('/_dusk/env', [
'middleware' => 'web',
'uses' => function () {
return response(getenv('APP_ENV'));
}
]);

The Custom Browser

Although Laravel\Dusk\Browser is macroable, I prefer to extend it instead of adding a macro to it.

Don’t forget to override newBrowser on DuskTestCase to instantiate your own Browser class instead.

protected function newBrowser($driver) {
return new Browser($driver);
}

Conclusion

That’s it! Now you can just assert that the environments matches whenever you feel like you’re stuck running your tests in the wrong database.

/**
* A basic browser test example.
*
*
@return void
*/
public function testBasicExample() {
$this->browse(function (Browser $browser) {
$browser->assertBrowserEnvironment()
->visit('/')
->assertSee('Laravel');
});
}